Sergey Kudryashov
Sergey Kudryashov

Reputation: 723

One event on several elements

I have this function:

function Any(){
  this.b1 = $("#but1")
  this.b2 = $('<div id="but2" />')
  this.func = function(){
     alert('hello')
  }
  this.b1.on('click',function(){
   this.func()
  })
  this.b2.on('click',function(){
   this.func()
  })


}

I want to do something like this:

(this.b1, this.b2).on('click',this.close)

Upvotes: 0

Views: 66

Answers (4)

d.raev
d.raev

Reputation: 9546

Using the advanced syntax of .on() you may attach a listener to
a defined and stable object/selector (this) to look for the even on
dynamic SubComponents/selectors (#but1, #but2)
witch may or may not exists ... or show up later.

this.on('click','#but1,#but2',this.close);

Or in the more general case:

document.on('click','#but1,#but2', function(){ $('#my_dialog').close});

Upvotes: 0

postgresnewbie
postgresnewbie

Reputation: 1468

$("#but1,#but2").on("click",function(){
this.func();
});

Upvotes: 0

Artyom Neustroev
Artyom Neustroev

Reputation: 8715

I would keep an array of selectors:

//code
    this.selectors = ["#but1", "#but2"];
    $(this.selectors.join(",")).on('click', this.close);
//code

Upvotes: 1

adeneo
adeneo

Reputation: 318182

You can use add()

this.b1.add(this.b2).on('click',this.close);

FIDDLE

Upvotes: 4

Related Questions