简体   繁体   English

HTML Mouseup一次缓存一个元素

[英]Html mouseup caching an element more than once

I've written a jquery script which works fine, but now I'm trying to make it into a plugin. 我已经编写了一个运行良好的jquery脚本,但是现在我试图将其制作为插件。 Once it's in the plugin though, the mouseup function on the html appears to increase the cache of the same element by one every time, and I can't figure out why. 一旦将其放入插件中,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>

If someone could explain why this is happening (in as much layman's terms as possible), I'd be very grateful. 如果有人能解释为什么会发生这种情况(尽可能多用外行的话),我将不胜感激。

Thanks 谢谢

You should tell us what you actuallywant to achieve but for a start: 您应该告诉我们您实际想要实现的目标,但要从头开始:

Every time you click the element, $(this).myPlugin() gets executed. 每次单击元素,都会执行$(this).myPlugin()
This function itself binds an event handler to the mouseup event, so every time you click the element, a new mouseup event handler is added (but they are all doing the same thing). 该函数本身将事件处理程序绑定到mouseup事件,因此, 每次单击该元素时,都会添加一个新的mouseup事件处理程序(但它们都在做相同的事情)。

So 所以

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

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

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