Javascript:“change"在Firefox中对html选择元素使用键盘时不会触发的事件
Javascript: "change" event not triggered when using the keyboard on a html select element in Firefox
如果你有一个select:
<select id="sel">
<option value="A">option A</option>
<option value="B">option B</option>
<option value="C">option C</option>
</select>
如果你聚焦选择,然后使用箭头来改变选中的选项,Firefox 30不会触发选中的"change"事件。这就是FF选择实施"变更"事件的方式,他们说这不会被修复(似乎这就是标准所说的)。
为了尝试解决这个问题,我们可以为"change"answers"keyup"事件注册处理程序,这样即使用户使用键盘,我们也能获得事件:
sel.addEventListener("change", handle_change);
sel.addEventListener("keyup", handle_change);
但是现在我们遇到了另一个bug http://jsfiddle.net/xLCNX/,当用户同时使用鼠标和键盘来选择选项时(使用鼠标选择选项B,使用键盘选择选项C,再次使用鼠标选择选项B -最后一个动作不会触发更改事件)。
要解决这个问题,你需要做的是把它放在事件处理程序中:
sel.value = sel.value;
代码来自fiddle:
HTML:<ol>
<li>with the mouse(!) select option <b>B</b>. Event <b>change</b> is triggered.</li>
<li>keyboard(!) press down arrow to select option <b>C</b>. Event <b>keyup</b> is triggered.</li>
<li>with the mouse(!) select option <b>B</b> again. No event is triggered<br>
Because we have selected the same option that was previously selected (<b>B</b>), there is no change so FF will not trigger a <b>change</b> event.<br>
When we select option <b>C</b> with the keyboard, only the displayed option and the <b>select.value</b> changed to option <b>C</b>. Somehow, internally, FF kept the original value, option <b>B</b>. So when we selected back option <b>B</b> FF decides that nothing changed. The problem is the inconsistency between what FF knows is the current value and the other two values: the displayed value and the <b>select.value</b> value.
</li>
</ol>
<select id="sel">
<option value="A">option A</option>
<option value="B">option B</option>
<option value="C">option C</option>
</select>
<ol id="log"></ol>
JS:
var handle_change = function() {
log.innerHTML += "<li>option " + sel.value + "</li>";
//uncomment this to fix the bug
//sel.value = sel.value;
};
var sel = document.getElementById("sel");
var log = document.getElementById("log");
sel.addEventListener("change", handle_change);
sel.addEventListener("keyup", handle_change);
要解决这个问题,您需要做的是将其放入事件处理程序中:
sel.value = sel.value;
这将设置FF保存的select的内部值与select中显示的值相同,该值也可以通过self .value.
相关文章:
- Vue键盘事件未启动
- Bootstrap 3键盘对默认键盘事件没有反应
- 是否可以使用JavaScript创建计算机宏(键盘事件等)
- JavaScript 键盘事件和比较
- 虚拟键盘事件
- 如何在 LimeJS javascript for html5 中处理键盘事件
- 调度键盘事件不'不能在JavaScript中工作
- 在谷歌地图上收听键盘事件
- 无法在鳄梨酱iframe中获取键盘事件
- 扩展浏览器以处理Apple键盘事件
- 用防油键或防篡改键触发键盘事件
- 如何使用自定义键盘事件和keyCode更改输入/textarea值
- 如何在svg上收听键盘事件
- 如何存储鼠标&键盘事件和值
- 键盘事件代码
- 国际键盘如何处理 JavaScript 键盘事件
- 来自键盘事件的 JS 读取变量
- 如何在 CodeMirror 中触发键盘事件
- 具有离子形式的键盘事件
- JavaScript 键盘事件未触发