当我们单击“为标签分配”复选框时,Chrome 和 IE 不会按时触发更改事件

Chrome and IE doesn't fire change event on time when we click on label assigned for checkbox

本文关键字:IE 事件 Chrome 单击 我们 标签 分配 复选框 为标签分配      更新时间:2023-09-26

在用户选中复选框的特定条件下,我想显示一条警报消息并取消选中该复选框,因此要取消选中复选框,我正在对其调用单击函数,以便它在内部取消选中并触发必要的事件。

我有一个复选框和标签,用于复选框,for标签正确设置了属性

  • 在 Firefox 中,取消选中适用于复选框及其标签。
  • 在 chrome 中,取消选中适用于复选框,但不适用于标签。
  • 在 chrome 中,取消选中不适用于复选框或标签。

通过特定的超时,我能够解决这个问题,但我想要一个不使用超时的解决方案。

您可以在此处查看代码并访问jsfiddle。

$("#id1").on("change", function(event) {
  if (event.target.checked) {
    $(event.target).trigger("click");
  }
});
$("#id2").on("change", function(event) {
  setTimeout(function() {
    if (event.target.checked) {
      $(event.target).trigger("click");
    }
  }, 5);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="checkbox" value="" id="id1">
<label for="id1">Click me</label>
<br/>
<input type="checkbox" value="" id="id2">
<label for="id2">Works with timeout</label>

This work quite well with Firefox but not in chrome and IE9, IE10

我正在寻找javascript或jQuery解决方案

试试这个:

$("#id1").change(function(event) {
  if (this.checked) {
    this.checked = false;
  }
});

我已经在Chrome中尝试过,它似乎可以工作,基本上不是单击复选框,而是修改其状态

斯菲德尔

更新了 JSFIDDLE 触发点击事件