2

Why i cant write variable as selector in "on" handler. How will be right?

var buttons = $('.sector').find('button');
$(document).on('click', buttons, function() { // here buttons not found
    //...
})

$(document).on('click', '.sector button', function() { // here works
    //...
})

Content can be after ajax request, so i need write $(document) not $(buttons) !?

bsbak
  • 719
  • 1
  • 6
  • 18
  • 1
    I think the base idea behind on() is to bind events on dynamic element... why you want to find it before. – Chaitanya Gadkari May 31 '15 at 11:54
  • 2
    Because that's just how `.on()` works. If you pass a selector as its second argument it must be a string. Your `buttons` variable will reference a jQuery object containing all of the button elements that exist within `.sector` *at the time that line runs* - it will not include future elements added after an ajax request. – nnnnnn May 31 '15 at 11:55
  • Dodgy but `var buttons = '.sector button';`. Your best bet is `$(document).on('click', '.sector button', function() {...})` – lshettyl May 31 '15 at 11:58

1 Answers1

1

You can bind it to the div parent to which you are updating content by ajax.

$('#ParentDivOfUpdateId').on('click', '.sector button', function() { 
    // here ParentDivOfUpdateId is Id of div which is parent to your dynamic content
    //...
})
Chaitanya Gadkari
  • 2,669
  • 4
  • 30
  • 54