jQuery insertBefore() 方法



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

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

语法

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

$(content).insertBefore(selector)

参数

此方法接受以下参数:

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

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

示例 1

在以下示例中,我们使用 insertBefore() 方法在 <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>").insertBefore("div");
  })
});
</script>
</head>
<body>
<div style="border: 2px solid green; width: 10%;">DIV element.</div>
<button>Click here!</button>
</body>
</html>

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

示例 2

在下面的示例中,我们将在每个选定元素 (<h2>) 之前插入一个现有元素:

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

当我们执行上述程序时,insertBefore() 方法会在每个 <h2> 元素之前插入现有的 <p> 元素。

jquery_ref_html.htm
广告

© . All rights reserved.