Live jQuery chain handlers?

I saved several divs in variables. I want to associate the same live handler with a bunch of divs. How to 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]
+3
source share
4 answers

Why not:

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

Thanks, you cannot combine multiple jQuery objects and then call . You need one selector. So either: .live().live()

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

or pre-define the function and attach it separately:

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

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

div1 jQuery,

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

jQuery $(div1)

0

live, click

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

, :

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

All Articles