簡體   English   中英

復選框點擊事件會中斷以運行代碼,但$ .trigger('click')只會在Chrome中識別,而不會在Firefox中識別。 為什么?

[英]A checkbox click event is interrupted to run code, but $.trigger('click') will only be recognized in Chrome, not Firefox. Why?

我有一個復雜的方案來中斷復選框點擊事件,所以我可以在點擊事件完成之前運行一些javascript / jQuery代碼(即選中框)。

但是,在Chrome(我的基礎瀏覽器)和Firefox(由我的一小部分用戶使用)中應用代碼時,我注意到了一些不同的行為。

在這個小提琴示例中 ,事件序列在Chrome中運行良好,但如果您在Firefox中嘗試相同,則編程.trigger('click')不會觸發事件偵聽器。 為什么? 我用$.trigger()搜索了它,也許與$.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> 

更新:我將我的代碼簡化為裸元素,我可以證明該行為特定於啟動對話框(或警報或任何模態),這會破壞firefox中的后續.trigger('click')方法。 簡化的例子

你真的需要禁用復選框嗎?
關閉模式時,將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> 

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM