概述 .one( events [, data ], handler(eventObject) )
返回值:jQuery
描述:为元素的事件添加处理函数。处理函数在每个元素上每种事件类型最多执行一次。
null
或被省略,那么被选中的元素总是能触发事件。
event.data
。
return false
的话,那么该参数位置可以直接简写成 false
。
null
或被省略,那么被选中的元素总是能触发事件。
event.data
。
.one()
和.on()
是相同的,
不同之处在于,对于给定的元素和事件类型,处理程序在第一次触发事件后会被立即解除绑定,举个示例:
- $( "#foo" ).one( "click", function() {
- alert( "This will be displayed only once." );
- });
在代码执行后,点击id为foo
的元素将显示警报。之后再在该元素上点击时,就不会再触发该事件。此代码是等效于:
- $( "#foo" ).on( "click", function( event ) {
- alert( "This will be displayed only once." );
- $( this ).off( event );
- });
换句话说,在一个普通的事件绑定处理函数中,显式的调用 .off()
和该方法的作用是一样的。
如果该方法的第一个参数包含多个用空格分隔的事件类型的话,那么每种类型的事件被触发时,处理函数仅会被每个事件类型调用一次。
- $( "#foo" ).one( "click mouseover", function() {
- alert( "The " + event.type + " event happened!" );
- });
在上面的示例中,由于两个事件类型(click
和 mouseover
),alert可以显示两次。
示例
为每个 div 绑定一次性 click 事件。
- <!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.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>
在每个段落上第一次点击时,显示该段落的内容:
- $("p").one("click", function(){
- alert( $(this).text() );
- });
处理函数在每个元素上每种事件类型只执行一次。
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <title>one demo</title>
- <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
- </head>
- <body>
-
- <div class="count">0</div>
- <div class="target">Hover/click me</div>
-
- <script>
- var n = 0;
- $(".target").one("click mouseenter", function() {
- $(".count").html(++n);
- });
- </script>
-
- </body>
- </html>