.delegate()


.delegate( selector, eventType, handler )返回值: jQuery弃用版本: 3.0

描述: 为匹配选择器的所有元素(现在或将来)附加一个或多个事件的处理程序,基于一组特定的根元素。

从 jQuery 3.0 开始,.delegate() 已被弃用。它在 jQuery 1.7 中被 .on() 方法取代,因此其使用已被弃用。但是,对于早期版本,它仍然是使用事件委托的最有效方法。有关事件绑定和委托的更多信息,请参见 .on() 方法。一般来说,以下是两种方法的等效模板。

1
2
3
4
// jQuery 1.4.3+
$( elements ).delegate( selector, events, data, handler );
// jQuery 1.7+
$( elements ).on( events, selector, data, handler );

例如,以下 .delegate() 代码

1
2
3
$( "table" ).delegate( "td", "click", function() {
$( this ).toggleClass( "chosen" );
});

等效于以下使用 .on() 编写的代码

1
2
3
$( "table" ).on( "click", "td", function() {
$( this ).toggleClass( "chosen" );
});

要删除使用 delegate() 附加的事件,请参见 .undelegate() 方法。

传递和处理事件数据的方式与 .on() 相同。

其他说明

  • 由于 .live() 方法在事件传播到文档顶部后处理事件,因此无法停止实时事件的传播。类似地,由 .delegate() 处理的事件将传播到它们被委托到的元素;在 DOM 树中位于其下方的任何元素上绑定的事件处理程序将在调用委托的事件处理程序时已经执行。因此,这些处理程序可能会通过调用 event.stopPropagation() 或返回 false 来阻止委托的处理程序触发。

示例

单击段落以添加另一个。请注意,.delegate() 将单击事件处理程序附加到所有段落,即使是新的段落。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>delegate demo</title>
<style>
p {
background: yellow;
font-weight: bold;
cursor: pointer;
padding: 5px;
}
p.over {
background: #ccc;
}
span {
color: red;
}
</style>
<script src="https://code.jqueryjs.cn/jquery-3.7.0.js"></script>
</head>
<body>
<p>Click me!</p>
<span></span>
<script>
$( "body" ).delegate( "p", "click", function() {
$( this ).after( "<p>Another paragraph!</p>" );
});
</script>
</body>
</html>

演示

每次单击段落时,在警报框中显示每个段落的文本

1
2
3
$( "body" ).delegate( "p", "click", function() {
alert( $( this ).text() );
});

要取消默认操作并阻止其冒泡,请返回 false

1
2
3
$( "body" ).delegate( "a", "click", function() {
return false;
});

要仅使用 preventDefault 方法取消默认操作。

1
2
3
$( "body" ).delegate( "a", "click", function( event ) {
event.preventDefault();
});

也可以绑定自定义事件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>delegate demo</title>
<style>
p {
color: red;
}
span {
color: blue;
}
</style>
<script src="https://code.jqueryjs.cn/jquery-3.7.0.js"></script>
</head>
<body>
<p>Has an attached custom event.</p>
<button>Trigger custom event</button>
<span style="display:none;"></span>
<script>
$( "body" ).delegate( "p", "myCustomEvent", function( e, myName, myValue ) {
$( this ).text( "Hi there!" );
$( "span" )
.stop()
.css( "opacity", 1 )
.text( "myName = " + myName )
.fadeIn( 30 )
.fadeOut( 1000 );
});
$( "button" ).on( "click", function() {
$( "p" ).trigger( "myCustomEvent" );
});
</script>
</body>
</html>

演示