繁体   English   中英

HTML Mouseup一次缓存一个元素

[英]Html mouseup caching an element more than once

我已经编写了一个运行良好的jquery脚本,但是现在我试图将其制作为插件。 一旦将其放入插件中,html上的mouseup函数似乎每次都会将同一元素的缓存增加一倍,我不知道为什么。

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Untitled Document</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.5.min.js"></script>
    </head>
    <body>
    <div class="box">Box 1</div>
    <script type="text/javascript">
    //<![CDATA[  

    $(function(){  

              (function($) {  

              $.fn.myPlugin = function() {  

                    return this.each(function(){  

                        var $this = $(this);  

                                               $('html').mouseup(function(){            

console.log('cached +1: ' +   $this);//this ouput increases by one every mouseup                                    

                                });//html mouseup  


                            console.log('cached once: ' + $this);// this output displays once per mouseup   


                      });// return this each  


                  } //fn myPlugin  

              })(jQuery);  


    $('.box').mousedown(function(){  

        $(this).myPlugin();  

        });//.box mousedown  


    });//document ready    

    //]]>
    </script>
    </body>
    </html>

如果有人能解释为什么会发生这种情况(尽可能多用外行的话),我将不胜感激。

谢谢

您应该告诉我们您实际想要实现的目标,但要从头开始:

每次单击元素,都会执行$(this).myPlugin()
该函数本身将事件处理程序绑定到mouseup事件,因此, 每次单击该元素时,都会添加一个新的mouseup事件处理程序(但它们都在做相同的事情)。

所以

  1. 单击: $(this).myPlugin(); 被调用-> 1 mouseup事件处理程序。
  2. 单击: $(this).myPlugin(); 被调用-> 2 mouseup事件处理程序。
  3. 单击: $(this).myPlugin(); 被调用-> 3个mouseup事件处理程序。
    等等

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM