2011-10-11 114 views
1

由於HTML的下面的代碼片段:jQuery的.live()忽略事件

Goggles <input type="checkbox" id="id_goggles_opt_in" name="goggles_opt_in"> 
    Approved <input type="checkbox" id="id_approved" name="approved"> 

和這個JavaScript:

$('#id_approved').live('click', function() { 
    alert('click is fine when selected by ID'); 
}); 

var $formInputs = $('.form input[type=text], .form input:file, .form textarea, .form select, .form input[type=checkbox]'); 

var $checkboxes = $formInputs.filter('[type=checkbox]'); 
console.log("This selector actually finds the elements: " + $checkboxes.size()); 
console.log($checkboxes) 

$checkboxes.live('click', function() { 
    alert('bizarrely this is never called'); 
}); 

第二警報從來沒有發射。 #jquery老客戶建議我只使用.delegate,但爲什麼這不起作用?

實施例上的jsfiddle:http://jsfiddle.net/amA3h/

回答

3

Mully是正確的 - 使用.filter().live()事件干涉。

這工作:

http://jsfiddle.net/mblase75/amA3h/5/

或者,要做到這一點.delegate風格:

$('.form').delegate('input:checkbox','click', function() { 
    alert('bizarrely this is never called'); 
}); 
+0

緩存不是問題http://jsfiddle.net/amA3h/6/,至少不是我看到的,看看這個小提琴,而問題正如Mully指出的那樣,實況方法應該總是在選擇器之後被調用。 –

+0

謝謝。看一下'delegate()',似乎更容易避免這個陷阱,因爲它將選擇器作爲參數。 –

5

jQuery's documentation

DOM遍歷會見hod不支持查找要發送到.live()的元素。相反,應該總是在選擇器之後直接調用.live()方法...