jQuery after() 方法



jQuery 中的 after() 方法用於在選定元素集中的每個元素之後插入內容或元素。

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

注意:如果我們想在選定元素之前插入內容,則需要使用before() 方法。

語法

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

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

引數

此方法接受以下引數:

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

示例 1

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

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

當我們點選按鈕時,after() 方法將在按鈕之後立即插入提供的段落元素。

示例 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").after(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").after(newParagraph);
      });
    });
  </script>
</head>
<body>
<button id="btn">Click me</button>
</body>
</html>

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

示例 4

我們將回調函式作為引數傳遞給 after() 方法。當呼叫 after() 時,將執行此函式,並返回要插入到按鈕之後的 內容。在我們的例子中,它建立了一個帶有當前日期和時間的新段落:

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

執行上述程式後,它將在按鈕之後立即新增提供的帶有當前日期和時間的段落。

jquery_ref_html.htm
廣告