jQuery连锁直播处理程序?

时间:2011-06-17 20:50:05

标签: jquery event-handling

我在变量中保存了几个div。我想将相同的活动处理程序绑定到一堆div。我该怎么做?

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]

4 个答案:

答案 0 :(得分:2)

由于.live()的工作方式,您无法组合多个jQuery对象,然后调用.live()。您需要一个选择器。所以要么:

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

或预先定义函数并单独附加:

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

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

答案 1 :(得分:1)

为什么不:

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

答案 2 :(得分:0)

由于div1已经是一个jQuery对象,你可以做到

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

没有换行是在jQuery选择器$(div1)

答案 3 :(得分:0)

您不需要live,只需使用click

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

如果您不想重写ID,可以这样做:

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');
});

演示:http://jsfiddle.net/roberkules/bvpNX/