jQuery——给元素添加父级的方法
生活随笔
收集整理的這篇文章主要介紹了
jQuery——给元素添加父级的方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
.wrap()
作用:在每個匹配的元素外層包上一個html元素
【例】給兩個span標簽分別添加父級
方法一:傳標簽?
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>div {background-color: #424242;width: 120px;height: 120px;margin-bottom: 5px;position: relative;}span {background-color: lightsteelblue;color: #fff;display: block;width: 80px;height: 80px;line-height: 80px;text-align: center;margin-bottom: 5px;}.active {position: absolute;left: 50%;top: 50%;margin-left: -40px;margin-top: -40px;}</style> </head> <body><span>span1</span><span>span2</span> </body> <script src="./jquery.js"></script> <script>$('span').addClass('active').wrap('<div class="wrapper"/>'); </script> </html>結果
可知給每個span標簽添加了div父級
方法二:傳函數(結果同上)
$('span').addClass('active').wrap(function (index) {return '<div class="wrapper' + index + '""></div>' })方法三:傳jQuery對象1——創建法(結果同上)
$('span').addClass('active').wrap($('<div class="wrapper"/>'));方法四:傳jQuery對象2——復制法
修改html代碼如下
<span>span1</span> <span>span2</span> <div class="wrapper"></div>js代碼
$('span').addClass('active').wrap($('.wrapper'));結果
即,對class為wrapper的div進行了復制,并包裹了兩個span標簽
.wrapAll()
作用:在所有匹配元素外面包一層HTML結構。
【例】給span標簽添加父級
代碼
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>div {width: 210px;padding: 40px;background-color: #424242;}span {margin: 0;padding: 0;display: inline-block;width: 100px;height: 100px;line-height: 100px;text-align: center;background-color: steelblue;color: #fff;}.demo {margin-right: 10px;}</style> </head> <body><span class="demo">span-1</span><span>span-2</span> </body> <script src="./jquery.js"></script> <script>$('span').wrapAll('<div>'); </script> </html>結果
?.wrapInner()
作用:在匹配元素里的內容外包一層結構。
【例】給inner中的文字包一層結構,效果如下
未操作之前
給文字包一層結構后
?
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>.wrapper {width: 300px;padding: 20px;border: 2px solid black;}.inner {padding: 20px;border: 2px solid steelblue;margin-bottom: 5px;text-align: center;color: #fff;}.new {height: 30px;background-color: teal;line-height: 30px;}</style> </head> <body><div class="wrapper"><div class="inner">星河滾燙,你是人間理想</div><div class="inner">皓月清涼,你是人間暑光</div></div> </body> <script src="./jquery.js"></script> <script>$('.inner').wrapInner('<div class="new"></div>'); </script> </html>.unWrap()
作用:將匹配元素集合的父級元素刪除,保留自身(和兄弟元素,如果存在)在原來的位置
【注】該方法不接受參數
總結
以上是生活随笔為你收集整理的jQuery——给元素添加父级的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jQuery——插入元素节点的方法
- 下一篇: jQuery——clone()方法