jQuery events on dynamically produced links
I have a list of links that are being created dynamically by another function they are in the form <a id="hi-1">test</a> <a id="hi-2">test</a>
etc.
I am trying to target these links and bind click/mouseover events开发者_如何学C to them. The following is the code for targeting one of these link(#hi-1):
$(function() {
$("#hi-1") .bind("mouseover", highlight);
$("#hi-1") .bind("mouseleave", highlight);
$("#hi-1") .bind("click", highlight);
});
function highlight(evt){
$("p#p-1").toggleClass("highlighted");
}
This should toggle the class name of .
I can't seem to get it to work, I believe it could be something to do with the fact that the links are created dynamically. However i have little jQuery experience and i may be going about it the wrong way.
Any Help is much appreciated.
Selectors apply at the time of creation. You select the elements, then you bind to those elements, not to the selector.
You can, however, make use of event bubbling -- ancestor elements are notified of events on child elements. jQuery provides a beautiful syntax for this with delegate
:
$('#containerElement').delegate('#hi-1', 'click mouseover mouseleave', highlight);
This assumes #containerElement
is an ancestor element of all elements that will be matched.
However, if you only have one element (as is suggested by giving it an ID) it might be easier simply to bind the handler at the time the element is created.
Try
$("#hi-1").live("mouseover mouseleave click", function(){
$("p#p-1").toggleClass("highlighted");
});
You should use the .live() method of jquery.
http://api.jquery.com/live/
Attach a handler to the event for all elements which match the current selector, now and in the future.
Example:
$('.clickme').live('mouseover', function() {
// live handler called
});
精彩评论