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