Javascript:“change"在Firefox中对html选择元素使用键盘时不会触发的事件

Javascript: "change" event not triggered when using the keyboard on a html select element in Firefox

本文关键字:键盘 事件 元素 选择 change quot html 中对 Firefox Javascript      更新时间:2023-09-26

如果你有一个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.

访问。