返回值:jQueryone(eventType, [eventData], handler(eventObject))
Attach a handler to an event for the elements. The handler is executed at most once per element.
-
1.1 新增one(eventType, [eventData], handler(eventObject))
eventType (String) A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names.eventData (Object) 可选参数,将要传递给事件处理函数的数据映射。handler(eventObject) (Function) 每当事件触发时执行的函数。
This method is identical to .bind()
, except that the handler is unbound after its first invocation. For example:
$('#foo').one('click', function() { alert('This will be displayed only once.'); });
After the code is executed, a click on the element with ID foo
will display the alert. Subsequent clicks will do nothing. This code is equivalent to:
$('#foo').bind('click', function(event) { alert('This will be displayed only once.'); $(this).unbind(event); });
In other words, explicitly calling .unbind()
from within a regularly-bound handler has exactly the same effect.
示例:
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="jquery.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>
演示:
示例:
To display the text of all paragraphs in an alert box the first time each of them is clicked:
jQuery 代码:
$("p").one("click", function(){
alert( $(this).text() );
});