开发者

jQuery's .live() ignoring events

Given the following snippet of HTML:

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

and this 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 = 开发者_如何学Python$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');
});

The second alert is never fired. #jquery regulars advised me to just use .delegate, but why doesn't this work?

Example on JSFiddle: http://jsfiddle.net/amA3h/


From jQuery's documentation:

DOM traversal methods are not supported for finding elements to send to .live(). Rather, the .live() method should always be called directly after a selector...


Mully is right -- using .filter() interferes with the .live() event.

This works:

var $checkboxes = $('.form input[type=checkbox]');
$checkboxes.live('click', function() {
    alert('bizarrely this is never called');
});

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

Or, to do it .delegate-style:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜