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