返回值:jQueryone(events, [data], handler(eventObject))

为元素的事件添加处理函数。该处理函数最多在每个满足条件的元素执行一次。

one(events, [data], handler(eventObject)) 这种用法和 .bind() 是一样的,不同之处在于,该处理函数在第一次被调用之后便会解除事件绑定。one(events, [selector], [data], handler(eventObject)) 这种用法是 jQuery 1.7 中添加的,它和 .on() 是一样的,不同之处在于,当满足选择器的被代理元素上的处理函数第一次被调用之后,便会解除事件绑定。例如:

$("#foo").one("click", function() {
  alert("This will be displayed only once.");
});
$("body").one("click", ".foo", function() {
  alert("This displays once for the first .foo clicked in the body.");
});

上述代码代码执行完之后,若在 ID 为 foo 的元素上发生的点击事件,那么就会显示提示框。之后再在该元素上点击时,就不会再触发该事件。上述代码等价于:

$("#foo").bind("click", function( event ) {
  alert("This will be displayed only once.");
  $(this).unbind( event );
});

换句话说,在一个普通的事件绑定处理函数中,显式的调用 .unbind() 和该方法的作用是一样的。

如果该方法的第一个参数包含多个用空格分隔的事件类型的话,那么每种类型的事件被触发时,处理函数仅会被调用一次

示例:

为每个 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="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>

演示:

示例:

在每个段落上第一次点击时,显示该段落的内容:

jQuery 代码:
$("p").one("click", function(){
alert( $(this).text() );
});