.undelegate()
返回: jQuery
.undelegate()
描述:针对所有匹配当前选择器的元素,从事件上删除一个处理函数。匹配元素基于一个特定的根元素集合。
加入于: 1.4.2
.undelegate()该签名不接受任何参数。
加入于: 1.4.2
.undelegate( selector, eventType )加入于: 1.4.2
.undelegate( selector, eventType, handler )加入于: 1.4.3
.undelegate( selector, events )- selector类型:String一个选择器,它用来筛选事件结果。
- events类型:PlainObject一个对象,它是一个或多个事件类型,以及先前绑定到这个事件上的函数,现在要解除对它们的绑定。
加入于: 1.6
.undelegate( namespace )- namespace类型:String一个字符串,包含了要解除绑定的事件的命名空间。
.undelegate()
方法是一个删除事件处理函数的方式,这些事件处理函数是先前用.delegate()
方法绑定的。自从jQuery 1.7,.on()
方法和.off()
方法优先附加事件处理函数、优先删除事件处理函数。
示例
可以向彩色按钮绑定事件并解除绑定事件。
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>undelegate demo</title> <style> button { margin: 5px; } button#theone { color: red; background: yellow; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <button id="theone">Does nothing...</button> <button id="bind">Bind Click</button> <button id="unbind">Unbind Click</button> <div style="display:none;">Click!</div> <script> function aClick() { $( "div" ).show().fadeOut( "slow" ); } $( "#bind" ).click(function() { $( "body" ) .delegate( "#theone", "click", aClick ) .find( "#theone" ).text( "Can Click!" ); }); $( "#unbind" ).click(function() { $( "body" ) .undelegate( "#theone", "click", aClick ) .find( "#theone" ).text( "Does nothing..." ); }); </script> </body> </html>
演示结果
要想从所有的段落文本上解除所有的委托事件,只要这么写:
$( "p" ).undelegate();
要想从所有段落文本上解除所有的click委托事件,只要这么写:
$( "p" ).undelegate( "click" );
要想解除委托先前绑定的处理函数,只要向提供一个函数,作为第三个参数:
var foo = function () { // 处理某些事件的代码 }; // ... 现在当点击段落文本时会调用foo ... $( "body" ).delegate( "p", "click", foo ); // ... foo will no longer be called. $( "body" ).undelegate( "p", "click", foo );
利用委托事件的命名空间来解除绑定所有的委托事件。
var foo = function() { // 处理某些事件的代码 }; // Delegate events under the ".whatever" namespace $( "form" ).delegate( ":button", "click.whatever", foo ); $( "form" ).delegate( "input[type='text'] ", "keypress.whatever", foo ); // Unbind all events delegated under the ".whatever" namespace $( "form" ).undelegate( ".whatever" );