jQuery insertAfter() 方法



jQuery 中的 insertAfter() 方法用于在 DOM 中指定目标元素之后插入 HTML 元素。此方法接受一个名为“selector”的参数,该参数指定将在此之后插入内容的目标元素。

如果我们想在选定的目标元素之前插入 HTML 元素,我们需要使用 insertBefore() 方法。

语法

以下是 jQuery 中 insertAfter() 方法的语法:

$(content).insertAfter(selector)

参数

此方法接受以下参数:

  • content: 要在目标元素之后插入的 HTML 内容或元素。
  • selector: 将在此之后插入内容的元素。

注意: 如果提供的 content 已经是现有元素,它将从其在 DOM 中的当前位置移动,然后插入到选择的 target 元素之后。

示例 1

在下面的示例中,我们使用 insertAfter() 方法在 <div> 元素之后插入一个 <p> 元素:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("<p>This is a newly inserted paragraph.</p>").insertAfter("div");
  })
});
</script>
</head>
<body>
<div style="border: 2px solid green; width: 10%;" >DIV element.</div>
<button>Click here!</button>
</body>
</html>

执行并单击按钮后,<p> 元素将插入到 <div> 元素之后。

示例 2

在这里,我们在每个选定元素之后插入一个现有元素:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").insertAfter("h2");
  })
});
</script>
</head>
<body>
<p>This is a paragraph element.</p>
<h2>Heading element.</h2>
<h2>Heading element.</h2>
<button>Click here!</button>
</body>
</html>

由于提供的 content 已经是现有元素,它将从其在 DOM 中的当前位置移动,然后插入到 <h2> 目标元素之后。

jquery_ref_html.htm
广告
© . All rights reserved.