本文通過實例講解jQuery中 insertBefore() 方法的用法,供有需要的朋友參考。
此方法把匹配的元素插入到另一個指定元素集合的前面。insertBefore() 與 insertAfter() 的作用正好相反。
代碼如下:$(selector).insertBefore(content)
參數說明:selector 定義要被插入的內容;content 定義在哪些元素之前插入內容。
代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="https://www.cnblogs.com/" />
<title>insertBefore()函數-博客園</title>
<style type="text/css">
p{
width:100px;
height:100px;
background-color:red;
}
div{
width:200px;
height:200px;
background-color:blue;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#bt").click(function(){
$("div").insertBefore("p");
})
});
</script>
</head>
<body>
<p></p>
<div></div>
<input type="button" value="點擊查看效果" id="bt" />
</body>
</html>
上述代碼可以把 div 元素插入到 p 元素的前面。需要特別注意的是,這裡的「插入」是把匹配元素移動到指定元素之前,而不是複製一份新的。希望本文所述對大家的jQuery程序設計有所幫助。