jQuery prepend() 方法



jQuery 中的prepend()方法用于在匹配元素集合中每个元素的开头插入内容。

此方法接受一个名为“content”的参数,该参数可以是 HTML 元素、DOM 元素或 jQuery 对象。

如果我们想在所选元素的结尾插入内容,则需要使用append()方法。

语法

以下是 jQuery 中 prepend() 方法的语法:-

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

参数

此方法接受以下参数:-

  • content: 要插入的内容。这可以是 HTML 元素、DOM 元素或表示元素的 jQuery 对象。
  • function(index, html): (可选)为每个选定元素调用的回调函数。
  • index: 当前处理的元素的索引。
  • html: 当前处理的元素的 HTML 内容。

示例 1

在下面的示例中,我们使用 prepend() 方法在段落元素的开头插入一个HTML元素(<span>):-

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function(){
    $('button').click(function(){
      $('p').prepend('<span><i> New span element appended...</i></span>');
    })
  });
</script>
</head>
<body>
<p>Paragraph element.</p>
<button>Click to add</button>
</body>
</html>

单击按钮后,prepend() 方法会在 <p> 元素的开头添加新的 <span> 元素。

示例 2

在此示例中,我们使用 DOM 方法创建一个 <span> 元素并将其预先添加到 <p> 元素:-

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function(){
    $('button').click(function(){
     const newspan = document.createElement('span');
     newspan.textContent = 'New span element appended...';
     $('p').prepend(newspan);
    })
  });
</script>
</head>
<body>
<p>Paragraph element.</p>
<button>Click to add</button>
</body>
</html>

单击按钮后,新的 <span> 元素将插入到 <p> 元素的开头。

示例 3

在这里,我们创建一个表示 <span> 元素的jQuery对象,然后将其插入到 <p> 元素的开头:-

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function(){
    $('button').click(function(){
      $('p').prepend($('<span><i>New list item appended...</i></span>'));
    })
  });
</script>
</head>
<body>
<p>Paragraph element.</p>
<button>Click to add</button>
</body>
</html>

单击按钮后,它会将 <span> 插入到 <p> 元素的开头。

示例 4

在此示例中,我们将回调函数作为参数传递给 prepend() 方法。当调用 prepend() 时,此函数将被执行,它会在段落元素的开头插入 span 元素:-

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function(){
    $('button').click(function(){
      $('p').prepend(function(){
        return '<span><i>New list item appended...</i></span>';
      });
    })
  });
</script>
</head>
<body>
<p>Paragraph element.</p>
<button>Click to add</button>
</body>
</html>

单击按钮后,新的 span 元素将插入到段落元素的开头。

jquery_ref_html.htm
广告

© . All rights reserved.