开发者

jQuery chain live handlers?

I have saved a few divs in variable开发者_开发知识库s. I want to bind the same live handler to a bunch of the divs. How do I do it?

var div1 = $('#selecto');
var div2 = $('#matic');
var div3 = $('#hello');
$(???).live('click', function() {
   console.log('one of those divs was clicked');
});
// I tried (unsuccessfully) replacing ??? with [div1, div2, div3]


Due to how .live() works, you cannot combine several jQuery objects and then call .live(). You need one selector. So either do:

$('#selecto, #matic, #hello').live('click', function() {
   console.log('one of those divs was clicked');
});

or define the function beforehand and attach it individually:

function log() {
   console.log('one of those divs was clicked');
}

div1.live('click', log);
div2.live('click', log);
div3.live('click', log);


Why not:

$('#selecto, #matic, #hello').live('click', function() {
   console.log('one of those divs was clicked');
});


Since div1 is already a jQuery object, you can just do

div1.live('click', function() {
   console.log('one of those divs was clicked');
});

without wrapping is in the jQuery selector $(div1)


you don't need live, just use click

div1.add(div2, div3).click(function(e){ ... });

if you don't wanna rewrite the IDs, you could do it this way:

var div1 = $('#selecto');
var div2 = $('#matic');
var div3 = $('#hello');

var selector = [];

div1.add(div2).add(div3).each(function(i, val) {
    selector.push("#" + val.id);
});

$(selector.join(", ")).live("click", function(e) {
    console.log(this.id + ' was clicked');
});

demo: http://jsfiddle.net/roberkules/bvpNX/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜