From 310fd066e91f454b990372ffa30e803cc8120975 Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 12:56:40 +0100 Subject: unslug zh-cn: move --- files/zh-cn/web/events/change/index.html | 124 ------------------------------- 1 file changed, 124 deletions(-) delete mode 100644 files/zh-cn/web/events/change/index.html (limited to 'files/zh-cn/web/events/change/index.html') diff --git a/files/zh-cn/web/events/change/index.html b/files/zh-cn/web/events/change/index.html deleted file mode 100644 index 6a997fc430..0000000000 --- a/files/zh-cn/web/events/change/index.html +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: change -slug: Web/Events/change -tags: - - Change - - HTML - - HTML DOM - - HTMLElement - - change vs. input - - 事件 - - 参考 -translation_of: Web/API/HTMLElement/change_event ---- -

{{APIRef}}

- -

当用户更改{{HTMLElement("input")}}、{{HTMLElement("select")}}和{{HTMLElement("textarea")}} 元素的值并提交这个更改时,change 事件在这些元素上触发。和 {{domxref("HTMLElement/input_event", "input")}} 事件不一样,change 事件并不是每次元素的 value 改变时都会触发。

- - - - - - - - - - - - - - - - - - - - -
冒泡
可取消
接口{{domxref("Event")}}
事件处理程序属性{{domxref("GlobalEventHandlers/onchange", "onchange")}}
- -

基于表单元素的类型和用户对标签的操作的不同,change 事件触发的时机也不同:

- - - -

示例

- -

<select> 元素

- -

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

结果

- - - -

文本输入元素

- -

对于一些元素,包括 <input type="text">change 事件在控件失去焦点前都不会触发。试一下在下面的输入框输入一些文字,然后点击输入框外的地方来触发事件。

- -

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

结果

- - - -

浏览器兼容性

- -

{{Compat("api.GlobalEventHandlers.onchange")}}

- -

对于一些特定类型的交互是否要触发 change 事件,不同浏览器的意见并不总是一致的。例如在 {{HTMLElement("select")}} 元素中使用键盘导航在 Gecko 中不会触发 change 事件,直到用户按下 Enter 键或将焦点从 <select> 上移走(参见 {{bug("126379")}})。但从 Firefox 63(Quantum)开始,这个行为在已经在主流浏览器中达成一致。

- -

参见

- -

{{domxref("NetworkInformation.connection")}} fires the change event when the connection information changes.

-- cgit v1.2.3-54-g00ecf