复选框点击事件会中断以运行代码,但$ .trigger('click')只会在Chrome中识别,而不会在Firefox中识别.为什么?

use*_*608 5 firefox jquery triggers google-chrome click

我有一个复杂的方案来中断复选框点击事件,所以我可以在点击事件完成之前运行一些javascript/jQuery代码(即选中框).

但是,在Chrome(我的基础浏览器)和Firefox(由我的一小部分用户使用)中应用代码时,我注意到了一些不同的行为.

在这个小提琴示例中,事件序列在Chrome中运行良好,但如果您在Firefox中尝试相同,则程序.trigger('click')不会触发事件侦听器.为什么?我用谷歌搜索了它,也许与该$.trigger()方法有关?

我的代码:

HTML:

<input type="checkbox" id="foo"> Clicky!

<hr>

<textarea id="bar"></textarea>

<hr>

<textarea id="cons"></textarea>
Run Code Online (Sandbox Code Playgroud)

JS(使用jQueryUI对话框)

$("#dialog").dialog({
  autoOpen: false
});

$("#foo").on('mousedown', function(e) {
  e.preventDefault(); // stop mousedown propagation
  $("#foo").prop('checked', false).prop("disabled", true); // disable checkbox from checking

  if (!$("#foo").is(":checked")) { // if not checked, run script

    // Open a modal while checkbox event is paused
    $("#dialog").dialog('open').dialog({
      title: "Hey! Here is a modal",
      modal: 'true',
      buttons: {
        "OK": function() {
          // run a script while modal running during checkbox pause
          $("#bar").val("checkbox paused, script run");
       
                       // release checkbox disable  &
          // programmatically complete the check
          $("#foo").prop('disabled', false);
          $("#foo")[0].click(); 
          // This click event completes and the click listener fires below in Chrome, but not on firefox? Why oh why?
          $("#dialog").dialog('close');
       
       }
        
      }
    });
  }
});



$("input:checkbox").on("click", function() {
  $("#cons").val("check completed!");
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<input type="checkbox" id="foo"> Clicky!

<hr>

<textarea id="bar"></textarea>

<hr>

<textarea id="cons"></textarea>

<div id="dialog">
  A modal opens
</div>
Run Code Online (Sandbox Code Playgroud)

更新: 我将我的代码简化为裸元素,我可以证明该行为特定于启动对话框(或警报或任何模态),这会破坏firefox中的后续.trigger('click')方法. 简化的例子

Kos*_*ery 1

您真的需要禁用该复选框吗?
当您关闭模式时,需要一些时间才能将disabled属性更改回false(在 Firefox 中)。因此,我们需要等待该复选框再次启用。否则,触发器会“点击”禁用的复选框,但不会产生任何结果。
看一下代码片段,我在触发器上设置了超时并且它有效:

$('#bar').on('click', function() {
  $("#foo").prop('disabled', true);
  alert("pause"); // alert, modal, dialog all break trigger event
  $("#foo").prop('disabled', false);
  // wait...
  setTimeout(function() {
    $("#foo").trigger('click')
  }, 100);
});

$("input:checkbox").on("change", function() {
  $("#baz").val("check completed!");
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="foo">
<hr>
<button id="bar">Checker</button>
<hr>
<textarea id="baz"></textarea>
Run Code Online (Sandbox Code Playgroud)

但可以用不同的方式解决。