小码哥的IT人生

首页 > JS > jQuery

jQuery 文档操作 - before() 方法 概述

jQuery 2022-06-01 15:24:02小码哥的IT人生shichen

jQuery 文档操作 - before() 方法

实例

在每个 p 元素前插入内容:

$("button").click(function(){
  $("p").before("<p>Hello world!</p>");
});

完整实例:

<html>
<head>
<script type="text/javascript" src="https://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $(".btn1").click(function(){
    $("p").before("<p>Hello world!</p>");
  });
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button class="btn1">在每个段落前面插入新的段落</button>
</body>
</html>

可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html

定义和用法

before() 方法在被选元素前插入指定的内容。

语法

$(selector).before(content)
参数 描述
content 必需。规定要插入的内容(可包含 HTML 标签)。

使用函数来插入内容

使用函数在指定的元素前面插入内容。

语法

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

完整实例:

<html>
<head>
<script type="text/javascript" src="https://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("p").before(function(n){
      return "<p>The p element below has index " + n + "</p>";
    });
  });
});
</script>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button class="btn1">在每个段落前面插入新的段落</button>
</body>
</html>

可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html

参数 描述
function(index)

必需。规定返回待插入内容的函数。

  • index - 可选。接收选择器的 index 位置。

版权所有 © 小码哥的IT人生
Copyright © phpcodeweb All Rights Reserved
ICP备案号:苏ICP备17019232号-2  

苏公网安备 32030202000762号

© 2021-2024