jQuery before() 方法



jQuery 中的 before() 方法用於在選定元素集中每個元素的 前面 插入內容或元素。

它接受一個引數 (content),該引數可以是:HTML 元素、DOM 元素、DOM 元素陣列或包含 DOM 元素的 jQuery 物件。

注意:如果我們想在選定元素的 後面 插入內容,我們需要使用 after() 方法。

語法

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

$(selector).before(content,function(index))

引數

此方法接受以下引數:

  • content: 要在每個選定元素之前插入的內容。可能的值可以是
  • HTML 元素
  • DOM 元素
  • jQuery 物件
  • function(index): (可選)在插入內容之前執行的回撥函式。
  • index: 它表示當前元素在匹配元素集中索引位置。

示例 1

在以下示例中,我們演示了使用作為引數提供的 HTML 元素的 before() 方法的基本用法:

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("button").before("<p>New paragraph inserted before the button.</p>");
      });
    });
  </script>
</head>
<body>
<button>Click me</button>
</body>
</html>

單擊按鈕後,此方法將在按鈕之前立即插入提供的段落元素。

示例 2

在此示例中,我們使用 DOM 方法建立一個新的段落元素,然後將其插入到按鈕之前:

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        // Creating a new paragraph element
        const newParagraph = document.createElement("p");
        newParagraph.textContent = "New paragraph added!";
        $("button").before(newParagraph);
      });
    });
  </script>
</head>
<body>
<button id="btn">Click me</button>
</body>
</html>

執行上述程式後,它將在按鈕之前立即插入提供的段落元素。

示例 3

在這裡,我們建立一個表示新段落元素的 jQuery 物件,然後將其插入到按鈕元素之前:

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        // Creating a new paragraph jQuery object
        const newParagraph = $("<p>New paragraph added!</p>");
        $("button").before(newParagraph);
      });
    });
  </script>
</head>
<body>
<button id="btn">Click me</button>
</body>
</html>

當我們執行上述程式時,它將在按鈕之前立即新增提供的段落元素。

示例 4

在此示例中,我們將 回撥函式作為引數傳遞給 before() 方法。當呼叫 before() 時,此函式將被執行,並返回要在按鈕之前插入的內容:

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("button").before(function(){
          return "<p>New paragraph added!</p>";
        });
      });
    });
  </script>
</head>
<body>
<button id="btn">Click me</button>
</body>
</html>

當我們執行上述程式時,它將在按鈕之前立即插入提供的段落。

jquery_ref_html.htm
廣告

© . All rights reserved.