2016-07-30 16 views
0


我試圖理解爲什麼在下面的例子中更改事件不會被觸發(我會告訴確切位置)。如果更改來源不是來自html的話,那麼javascript事件不會被觸發?

我有一個複選框,讓我們把它叫做「mainCheckbox」,選中後 - 我要檢查一些其他相關的複選框(到目前爲止工作)。

此外,當我取消了相關的複選框(子複選框)中的一個 - 我要取消的mainChecbox,這也適用 - 但這裏是什麼我不理解:

我改變checked屬性在mainCheckbox(在「childCheckbox」的onChange處理)的

怎麼就mainCheckbox的onChange處理不會被調用?
或者主複選框的onchange事件沒有被觸發?

這裏是代碼:

//binding to the 'mainCheckbox' change event: 
$("[data-role='group']").bind("change", function(event){ 
    //checking/unchecking all related checkboxes respectivly 
    $("li input[data-group='" + event.target.id + "'").prop('checked', $(this).prop("checked")); 
}) 

//binding to the change event of every 'child checkbox' 
$("li input[data-group]").bind("change", function(){ 
    if (event.target.checked){ 
     //if the child checkbox is now checked - I am checking if now all child checkboxes are checked, 
     //if so - I need to check the main checkbox. 
     if ($("[data-group=" + event.target.dataset.group + "]:checked").length == $("[data-group=" + event.target.dataset.group + "]").length){ 
      $("#" + event.target.dataset.group).prop("checked", true); 
     } 
     //TODO: add this device to the selectedDevices array. 
    } 
    else { 
     //the checkbox is now unchecked - so I am unchecking the main checkbox - 
     //but here is my failing to understand part: I am unchecking the main checkbox - 
     //why the change event is not triggered? I thought that now all child checkboxes will be unchecked as well 
     //(I am happy they are not :) just failing to understand why)... 
     $("#" + event.target.dataset.group).prop("checked", false); 
     //TODO: remove this device from the selectedDevices array. 

    } 

}) 

在此先感謝所有的反應,
吉米

+1

您是否在更改處理程序中更改主複選框的「單擊」屬性?這是一個錯字嗎? – marekful

+0

錯字!編輯。 – JimmyBoy

回答

2

在一般情況下,事件響應僅被炒到用戶行動,不行動碼。在複選框上設置checked屬性不會觸發其change事件; 用戶更改複選框的選中狀態。

這也是當您使用代碼來設置inputvalue真,selectedIndex(或value)一select的等

這也是事實相對於上form元素submit事件:調用一個HTMLFormElementsubmit功能將提交表單,而不會觸發其submit事件。 ,如果你使用jQuery提交表單(例如,如果你的HTMLFormElement纏jQuery對象上調用submit),它確實觸發其submit事件處理程序。這是jQuery API設計的一個不幸的副產品。

如果要觸發一個事件,你可以做到這一點與jQuery的trigger功能。所以如果合適的話,在設置​​checked之後,你可以設置.trigger("change")。一般來說,我提倡而不是生成類似的合成預定義事件(而不是調用需要調用的任何函數,或使用綜合自定義事件),但有一些有效的用例。當元素失去焦點

+0

另外,你應該看看jQuery.trigger http://api.jquery.com/trigger/這是你可以如何以porgraphally的方式執行某些事件處理程序。 – marekful

1

onchange事件被觸發。由於您正在以編程方式更改該值,因此您正在更改的元素從不會失去焦點。您可能希望檢查事件。

+0

如果您通過代碼更改複選框,則「輸入」不會觸發。這裏的根本與焦點無關。其根本在於它是一個*用戶操作*還是程序代碼。 –

+0

你很可能是對的。我沒有檢查,說實話。 – FDavidov

相關問題