[英]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
事件處理程序(但它們都在做相同的事情)。
所以
$(this).myPlugin();
被調用-> 1 mouseup
事件處理程序。 $(this).myPlugin();
被調用-> 2 mouseup
事件處理程序。 $(this).myPlugin();
被調用-> 3個mouseup
事件處理程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.