欢迎来到飞鸟慕鱼博客,开始您的技术之旅!
当前位置: 首页前端设计正文

jQuery中wrap、wrapAll和wrapInner用法以及区别

墨初 前端设计 4784阅读

网站制作中的一些交到计设是离不开JavaScript脚本语言的,而javascript中的一个著名的操作DOM对象的插件JQuery可以说是应用范围最广一款JS插件之一。今天我们记录一下,利用JQuery把DOM中某个节点用其它标记包裹起来的例子

将某个节点用其它标签包裹起来,JQuery中提供了三种方法,即wrap()方法,wrarAll()方法和wrarInner()方法。

jQuery中的wrap()方法使用

jQuery中的wrap() 方法把每个被选元素放置在指定的 HTML 内容或元素中

jQuery中的wrap()方法使用

例子:

HTML代码

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button class="btn1">用DIV包裹P标签</button>

JQ代码:

$(".btn1").click(function(){
    $("p").wrap("<div></div>");
});

结果:

我们查看源代码会变成这样

<div><p>This is a paragraph.</p></div>
<div><p>This is another paragraph.</p></div>

jQuery中的wrapAll()方法

jQuery中的wrapAll方法会在指定的 HTML 内容或元素中放置所有被选的元素。

jQuery中的wrapAll()方法

例子:

HTML代码

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button class="btn1">用DIV包裹P标签</button>

jQ代码:

$(".btn1").click(function(){
    $("p").wrapAll("<div></div>");
 });

结果:

查看源代码

<div>
    <p>This is a paragraph.</p>
    <p>This is another paragraph.</p>
</div>

jQ中的wrapInner()方法

jQuery中的wrapInner()方法使用指定的 HTML 内容或元素,来包裹每个被选元素中的所有内容 (inner HTML)。

jQ中的wrapInner()方法

例子:

HTML代码

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button class="btn1">用DIV包裹P标签内容</button>

jQ代码:

$(".btn1").click(function(){
    $("p").wrapInner("<div></div>");
});

结果:

查看源代码

<p>
    <div>This is a paragraph.</div>
</p>
<p>
    <div>This is another paragraph.</div>
</p>
声明:无特别说明,转载请标明本文来源!