jQuery append() 方法



jQuery 中的 append() 方法用於將內容插入到匹配元素集合中每個元素的 末尾

此方法接受一個名為“content”的引數,該引數可以是 HTML 元素、DOM 元素或 jQuery 物件。

如果我們想將內容插入到所選元素的 開頭,我們需要使用 prepend() 方法。

語法

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

$(selector).append(content,function(index,html))

引數

此方法接受以下引數:

  • content: 要附加的內容。這可以是 HTML 元素、DOM 元素或表示元素的 jQuery 物件。
  • function(index,html): (可選)為每個附加的元素執行的回撥函式。
  • index: 當前處理的元素的索引。
  • html: 當前處理的元素的 HTML 內容。

示例 1

在下面的示例中,我們使用 append() 方法將一個 HTML 元素(<li>)列表項插入到有序列表(<ol>)中:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function(){
    $('button').click(function(){
      $('ol').append('<li>New list item appended!</li>');
    })
  });
</script>
</head>
<body>
  <ol>
    <li>List item.</li>
    <li>List item.</li>
  </ol>
<button>Click to add</button>
</body>
</html>

單擊按鈕後,append() 方法會在有序列表的末尾新增一個新的列表元素(<li>)。

示例 2

在這個示例中,我們使用 DOM 方法建立一個 <li> 元素並將其插入到有序列表中:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function(){
    $('button').click(function(){
     const newlist = document.createElement('li');
     newlist.textContent = 'New list item appended!';
     $('ol').append(newlist);
    })
  });
</script>
</head>
<body>
  <ol>
    <li>List item.</li>
    <li>List item.</li>
  </ol>
<button>Click to add</button>
</body>
</html>

單擊按鈕後,新的 <li> 元素將插入到有序列表中。

示例 3

在這裡,我們建立一個表示 <li> 元素的 jQuery 物件,然後將其插入到有序列表中:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function(){
    $('button').click(function(){
      $('ol').append($('<li>New list item appended!</li>'));
    })
  });
</script>
</head>
<body>
  <ol>
    <li>List item.</li>
    <li>List item.</li>
  </ol>
<button>Click to add</button>
</body>
</html>

單擊按鈕後,append() 方法會在有序列表的末尾新增一個新的列表元素(<li>)。

示例 4

在這個示例中,我們傳遞一個 回撥 函式作為引數給 append() 方法。當呼叫 append() 時,此函式將被執行,並將一個新的列表元素附加到有序列表中:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function(){
    $('button').click(function(){
      $('ol').append(function(){
        return '<li>New list item appended!</li>';
      });
    })
  });
</script>
</head>
<body>
  <ol>
    <li>List item.</li>
    <li>List item.</li>
  </ol>
<button>Click to add</button>
</body>
</html>

單擊按鈕後,新的 <li> 元素將插入到有序列表中。

jquery_ref_html.htm
廣告
© . All rights reserved.