jQuery before() 方法用于在被选元素之前插入指定内容。如果是选择了多个匹配的元素则插入多个。

语法

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

方法参数

参数说明
content为必填参数。它指定要插入的内容。它的可能值是:HTML 元素、Query 对象、DOM 元素
function (index)它指定一个函数,返回用于插入的内容。索引:提供元素在集合中的索引位置。

例子

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").before("<p><b>www.yxjc123.com</b></p>");
    });
});
</script>
</head>
<body>
<button>在每个 p 元素之前插入内容</button>
<p>jQuery before() 方法</p>
<p>演示jQuery before() 方法的用法。</p>
</body>

</html>