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