change event is fired for <input> , <select> ,和 <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 .

冒泡 Yes
可取消 No
接口 事件
事件处理程序特性 onchange

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 .

范例

<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}`;
});
						

结果

Text input element

For some elements, including <input type="text"> 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;
}
						

结果

规范

规范 状态
HTML 实时标准
The definition of 'change' in that specification.
实时标准

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
onchange Chrome 1 Edge 12 Firefox 1 IE 9 Opera 9 Safari 3 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0

图例

完整支持

完整支持

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 never fired a change event in Gecko until the user hit Enter or switched the focus away from the <select> (见 bug 126379 ). Since Firefox 63 (Quantum), this behavior is consistent between all major browsers, however.

另请参阅

元数据

  • 最后修改: