jQuery bind or live not working as expected in my plugin
I'm writing a plugin for jQuery that wraps a span element around an input (text) element. When I bind() or live() the form element input to add/remove classes to its parent开发者_如何学Go element, the binding does not work. Consider the following;
(function($){
$.fn.MyPlugin = function() {
var $this, $tag;
return this.each(function(){
$this = $(this);
$tag = $(document.createElement('span'));
$this.wrap($tag).bind('mouseover',function(){
$tag.addClass('hover');
});
}
})(jQuery);
Using Google Chrome and viewing the elements and console output, I expect to see the 'hover' class added to the span element when I move my simulate a mouseover event. However nothing happens. If I print the $tag variable to the console after I add the hover class, it does appear correct in the console output.
I'm guessing this has something to do with variable scope but I'm lost trying to work out a solution.
Try using this:
(function($){
$.fn.MyPlugin = function() {
return this.each(function(){
$(this).wrap('<span>').bind('mouseover',function(){
$(this).parent().addClass('hover');
});
});
};
})(jQuery);
wrap
, when used with a jQuery object or a DOM element, clones that element and uses the copy to wrap the selection. From the API:
[wrap] doesn't move the object but just clones it to wrap around its target
Your code is adding a class to an element that has never been inserted into the DOM.
Try
return this.each(function(){
$this = $(this);
$tag = $(document.createElement('span'));
$this.wrap($tag);
$tag.bind('mouseover',function(){
$tag.addClass('hover');
});
}
If I'm not mistaken does wrap return $this
in this case.
(function($){
$.fn.MyPlugin = function() {
return this.each(function(){
$(this).wrap("<span></span>")
$(this).parent('span').live('mouseover',function(){
$(this).addClass('hover');
});
});
}
})(jQuery);
精彩评论