HTMLElement: change event - Web APIs 编辑

The change event is fired for <input>, <select>, and <textarea> elements when an alteration to the element's value is committed by the user. Unlike the input event, the change event is not necessarily fired for each alteration to an element's value.

BubblesYes
CancelableNo
InterfaceEvent
Event handler propertyonchange

Depending on the kind of element being changed and the way the user interacts with the element, the change event fires at a different moment:

The HTML specification lists the <input> types that should fire the change event.

Examples

<select> element

HTML

<label>Choose an ice cream flavor:
  <select class="ice-cream" name="ice-cream">
    <option value="">Select One …</option>
    <option value="chocolate">Chocolate</option>
    <option value="sardine">Sardine</option>
    <option value="vanilla">Vanilla</option>
  </select>
</label>

<div class="result"></div>
body {
  display: grid;
  grid-template-areas: "select result";
}

select {
  grid-area: select;
}

.result {
  grid-area: result;
}

JavaScript

const selectElement = document.querySelector('.ice-cream');

selectElement.addEventListener('change', (event) => {
  const result = document.querySelector('.result');
  result.textContent = `You like ${event.target.value}`;
});

Result

Text input element

For some elements, including <input type="text">, the change event doesn't fire until the control loses focus. Try entering something into the field below, and then click somewhere else to trigger the event.

HTML

<input placeholder="Enter some text" name="name"/>
<p id="log"></p>

JavaScript

const input = document.querySelector('input');
const log = document.getElementById('log');

input.addEventListener('change', updateValue);

function updateValue(e) {
  log.textContent = e.target.value;
}

Result

Specifications

SpecificationStatus
HTML Living Standard
The definition of 'change' in that specification.
Living Standard

Browser compatibility

BCD tables only load in the browser

Different browsers do not always agree whether a change event should be fired for certain types of interaction. For example, keyboard navigation in <select> elements used to never fire a change event in Gecko until the user hit Enter or switched the focus away from the <select> (see bug 126379). Since Firefox 63 (Quantum), this behavior is consistent between all major browsers, however.

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:166 次

字数:6827

最后编辑:8 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文