jQuery appendTo() 方法



jQuery 中的 appendTo() 方法用於將 HTML 元素追加到匹配元素集的末尾。此方法接受一個名為“selector”的引數,該引數指定將內容追加到末尾的目標元素。

如果我們想將 HTML 元素追加到所選目標元素的開頭,我們需要使用prependTo() 方法。

語法

以下是 jQuery 中 appendTo() 方法的語法:

$(content).appendTo(selector)

引數

此方法接受以下引數:

  • content: 要追加到目標元素末尾的 HTML 元素。
  • selector: 將內容追加到的目標元素。

注意:如果提供的content 已經是現有元素,它將從 DOM 中的當前位置移動,然後插入到所選目標元素的末尾。

示例 1

在以下示例中,我們使用 appendTo() 方法將 <span> 元素追加到 <p> 元素的末尾:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("<span><i> This is a newly appended span element.</i></span>").appendTo("p");
  })
});
</script>
</head>
<body>
<p>Paragraph element.</p>
<button>Click here!</button>
</body>
</html>

執行並點選按鈕後,<span> 元素將追加到 <p> 元素的末尾。

示例 4

在下面的示例中,我們將一個現有元素 (<span>) 追加到段落元素的末尾:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("span").appendTo("p");
  })
});
</script>
</head>
<body>
<span><i> This is a newly appended span element.</i></span>
<p>Paragrapah element.</p>
<button>Click here!</button>
</body>
</html>

由於提供的 content 已經是現有元素,它將從 DOM 中的當前位置移動,然後插入到 <p>(目標元素)之後。

jquery_ref_html.htm
廣告

© . All rights reserved.