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

问题描述 投票:5回答:1

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

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

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

我的代码:

HTML:

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

<hr>

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

<hr>

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

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!");
});
<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>

Update: I simplified my code to the bare elements and I can demonstrate the behavior is specific to launching the dialog (or alert or any modal), which breaks the subsequent .trigger('click') method in firefox. simplified example
jquery google-chrome firefox triggers click
1个回答
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!");
});
<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>

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

© www.soinside.com 2019 - 2024. All rights reserved.