Jquery event registration on dynamic elements
I have an event handler registration code like this
$("sel").each(function() {
(function(a){
var b = createb();
//do some more ops
a.addEventListener('evttype',handler1(a, b),false);
b.addEventListener('evttype',handler2(a, b),false);
})(this);
});
This binds the even 'eventtype' with all the element (a) selected by ("sel") , and also creates another element(b) and bind to it as well. It only works for static elements, of course. Now I want to register for all 'a' which are dynamically created. I read ab开发者_如何学编程out two API for this live() and delegate(). I could not think a way to make this work.
$('sel').delegate("a", "evttype", function(){
var b = createb();
//do some more ops
b.addEventListener('evttype',handler2(a, b),false);
});
the code is wrong as it creates a 'b' every time the event is handled. This is not the same as the first block of code. I only need to create the element 'b' once, and bind the same event to both of it, and they handle them separately. Is there an interface to match all the future elements based on the selector, or is there an easy way with delegate().
thanks for ur time. bsr.
there is http://api.jquery.com/live exactly for that purpose
You should check if your b
element exists before creating it.
$('sel').delegate("a", "evttype", function(){
if(!b_exists()){
var b = createb();
//do some more ops
b.addEventListener('evttype',handler2(a, b),false);
}
});
But, to give you the logic of the b_exists()
method, we need your markup and js.
Hope this helps. Cheers
精彩评论