Alert running multiple times using the plugin

I am working on this plugin

HTML

<span class="item" data-item="first">
</span>
<br><br>  

<span class="item" data-item="second">
</span>
<br><br>    

<span class="item" data-item="third">
</span>

JQUERY

(function($){
  $.fn.myPlugin = function(){
    return this.each(function(){

          for (var i = 1; i <= 2; i++) {
            $(this).append('<span class="act" title="active '+i+'">act'+i+'</span><br>');
        }        

          $('.act').bind({
        mouseover :function(){
          var item=$(this).parent().attr('data-item');
          alert(item);
        }             

      });          

    });
  };
})(jQuery);

$(document).ready(function()
{
$('.item').myPlugin();

});

When i hover on act it fires alert 3 times ie. the number of .item present below it. Whats the problem here?

Demo http://jsbin.com/IWutoQa/1/

You are adding a mouseover handler to each .act element in every loop. Instead, use a single delegated handler:

(function($){
    $.fn.myPlugin = function(){
        $(this).on('mouseover', '.act', function(){
            var item = $(this).parent().attr('data-item');
            alert(item);
        });    

        return this.each(function() {
            for (var i = 1; i <= 2; i++) {
                $(this).append('<span class="act" title="active '+i+'">act'+i+'</span><br>');
            }
        });
    };
})(jQuery);

$(document).ready(function() {
    $('.item').myPlugin();
});

Updated JSBin

我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章