jquery

jQuery的delegate()函数怎么使用

小亿
102
2023-09-08 04:50:38
栏目: 编程语言

jQuery的delegate()函数用于将事件绑定到被选元素的子元素上,即可以绑定动态生成的元素。

delegate()函数的语法如下:

$(selector).delegate(childSelector, event, handler);

其中,参数说明如下:

下面是一个使用delegate()函数的示例,将点击事件绑定到父元素的子元素上:

<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("ul").delegate("li", "click", function(){
$(this).toggleClass("selected");
});
});
</script>
<style>
.selected {
background-color: yellow;
}
</style>
</head>
<body>
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
<li>List item 4</li>
<li>List item 5</li>
</ul>
</body>
</html>

在上面的示例中,我们将点击事件绑定到ul元素的子元素li上,当点击li元素时,会切换选中样式。

0
看了该问题的人还看了