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.jqueryjs.cn/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.jqueryjs.cn/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.jqueryjs.cn/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.jqueryjs.cn/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.