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.jquery.com/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.jquery.com/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.