.one()
.one( eventType, [ eventData ], handler(eventObject) ) 返回: jQuery
描述: 附加一個處理事件到元素。處理函數(shù)在每個元素上最多執(zhí)行一次。
-
version added: 1.1.one( eventType, [ eventData ], handler(eventObject) )
eventType一個包含一個或多個JavaScript事件類型的字符串,比如"click"或"submit,"或自定義事件的名稱。
eventData將要傳遞給事件處理函數(shù)的數(shù)據(jù)映射。
handler(eventObject)每當(dāng)事件觸發(fā)時執(zhí)行的函數(shù)。
這種方法是和.bind()相同的 ,但該處理函數(shù)第一次調(diào)用后就解除綁定。舉個例子:
$('#foo').one('click', function() {
alert('This will be displayed only once.');
});
在代碼執(zhí)行后,點擊id為foo的元素將顯示警報。隨后的每次點擊什么都不做。此代碼是等效于:
$('#foo').bind('click', function(event) {
alert('This will be displayed only once.');
$(this).unbind(event);
});
換句話說,從一個定期綁定處理函數(shù)顯式調(diào)用.unbind()具有完全相同的效果。
Examples:
Example: Tie a one-time click to each div.
<!DOCTYPE html>
<html>
<head>
<style>
div { width:60px; height:60px; margin:5px; float:left;
background:green; border:10px outset;
cursor:pointer; }
p { color:red; margin:0; clear:left; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<p>Click a green square...</p>
<script>
var n = 0;
$("div").one("click", function(){
var index = $("div").index(this);
$(this).css({ borderStyle:"inset",
cursor:"auto" });
$("p").text("Div at index #" + index + " clicked." +
" That's " + ++n + " total clicks.");
});
</script>
</body>
</html>
Demo:
Example: To display the text of all paragraphs in an alert box the first time each of them is clicked:
$("p").one("click", function(){
alert( $(this).text() );
});