Using jQuery live with context
I wrote a plugin for jQuery but now my users are asking f开发者_运维百科or the ability to run my plugin on various elements on the same page so I'm trying to rewrite it a bit.
I'm having issues with my events.
here is what was working.
$(".jTagLabels label").live('mouseenter',function(){
$("#"+$(this).attr('rel')).css('opacity',1).find("span").show();
$(".jTagDeleteTag").show();
});
Now I'm trying to register this event on specific context but It's not working.
$(".jTagLabels label",container).live('mouseenter',function(){
$("#"+$(this).attr('rel')).css('opacity',1).find("span").show();
$(".jTagDeleteTag",container).show();
});
console.log(container) returns the right dom element...
It may be important to say that when I setup the event there is no jTagLabels created and that's why I'm using the live() function...
Use delegate()
, it's a lot cleaner and that's what it was made for, even though the resulting code could be the same.
Also depending on your code context, your container
variable is likely to lose its value between binding the event and triggering it.
$(container).delegate(".jTagLabels label",'mouseenter',function(){
var $this = $(this);
$("#"+$this.attr('rel')).css('opacity',1).find("span").show();
// There should be an easier way to find your container,
// like .closest('.someclass')
$this.parent().parent().find('.jTagDeleteTag').show();
});
精彩评论