如何使用jQuery点击一个段落并添加另一个段落
在这篇文章中,我们将学习如何使用jQuery在点击一个段落时向文档添加另一个段落。
方法:我们将使用jQuery的delegate()和after()方法。delegate()方法是用来添加事件监听器到给定的元素。这将被用来为段落元素添加一个点击事件监听器。这个方法,需要三个参数,在我们的例子中,子选择器是段落元素,事件是 “点击”,函数是一个匿名函数。
匿名回调函数用于向文档添加一个新的段落。这是通过after()方法完成的,该方法将给定的元素插入到文档中选定的元素之后。我们将使用this绑定作为选择器,在当前的段落之后插入一个新的段落元素。因此,这将在文档中被点击的那个元素之后添加一个段落元素。我们还可以添加一个计数器变量来查看这个效果。
语法:
$(selector).delegate("target_elem", function() {
$(this).after("content");
})
下面的例子展示了这种方法。
示例:
<html>
<head>
<style>
p {
background: green;
color: white;
padding: 5px;
}
</style>
<!--Include the jQuery library-->
<script src=
"https://code.jquery.com/jquery-git.js">
</script>
</head>
<body style="text-align: center;">
<h1 style="color: green;">
GeeksforGeeks
</h1>
<p>
Click on the paragraphs to start
adding new paragraphs
</p>
<script>
// A count variable to keep track
// of the current paragraph
let cnt = 0;
// Add the click event listener to
// the required paragraph element
("body").delegate("p", "click",
function() {
// Insert a new paragraph after
// this paragraph
(this).after(
"<p>New paragraph " +
cnt + "</p>
");
cnt++;
});
</script>
</body>
</html>
输出: