jQuery之常用且重要方法梳理(siblings,nextAll,end,wrap,apply,call,each)-(二)

时间:2024-03-25 22:07:38

1.siblings()

    siblings() 获得匹配集合中每个元素的同胞,通过选择器进行筛选是可选的。

<body>
<div><span>Hello</span></div>
<p class="selected">Hello Again</p>
<p>And Again</p> <script>
$("p").siblings(".selected").css("background", "yellow");
</script> </body>

结果:jQuery之常用且重要方法梳理(siblings,nextAll,end,wrap,apply,call,each)-(二)

2.nextAll()

    nextAll() 方法返回被选元素的所有跟随的同胞元素。

<script>
$(document).ready(function(){
$("h2").nextAll().css({"color":"red","border":"2px solid red"});
});
</script>
</head>
<body class="siblings"> <div>div (父)
<p>p</p>
<span>span</span>
<h2>h2</h2>
<h3>h3</h3>
<p>p</p>
</div> </body>

结果:jQuery之常用且重要方法梳理(siblings,nextAll,end,wrap,apply,call,each)-(二)

3.end()

    end() 方法结束当前链条中的最近的筛选操作,并将匹配元素集还原为之前的状态。

<head>
<style>p { margin:10px; padding:10px; }</style>
<script type="text/javascript" src="/jquery/jquery.js"></script>
</head> <body>
<p><span>Hello</span>, how are you?</p>
<script>$("p").find("span").end().css("border", "2px red solid");</script>
</body>

结果:jQuery之常用且重要方法梳理(siblings,nextAll,end,wrap,apply,call,each)-(二)

4.wrap(wrapper)

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

<script type="text/javascript">
$(document).ready(function(){
$(".btn1").click(function(){
$("p").wrap("<div></div>");
});
});
</script>
<style type="text/css">
div{background-color:yellow;}
</style>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button class="btn1">用 div 包裹每个段落</button>
</body>

结果:jQuery之常用且重要方法梳理(siblings,nextAll,end,wrap,apply,call,each)-(二)

wrap(function())

    使用函数来规定在每个被选元素周围包裹的内容。

<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").wrap(function(){
return "<div></div>"
});
});
}); </script>
<style type="text/css">
div{background-color:yellow;padding:10px;}
</style>
</head> <body>
<p>这是一个段落。</p>
<button>用 div 元素来包围 p 元素</button>
</body>

结果:jQuery之常用且重要方法梳理(siblings,nextAll,end,wrap,apply,call,each)-(二)

5.each()

    each() 方法规定为每个匹配元素规定运行的函数。(提示:返回 false 可用于及早停止循环。)

<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("li").each(function(){
alert($(this).text())
});
});
});
</script>
</head>
<body>
<button>输出每个列表项的值</button>
<ul>
<li>Coffee</li>
<li>Milk</li>
<li>Soda</li>
</ul>
</body>

结果:jQuery之常用且重要方法梳理(siblings,nextAll,end,wrap,apply,call,each)-(二)

6.call()

    调用一个对象的一个方法,以另一个对象替换当前对象。

apply()

    应用某一对象的一个方法,用另一个对象替换当前对象。

提示:call与apply的不同就是call传的值可以是任意的,而apply传的剩余值必须为数组。

function add(a, b) { return a + b; }

function sub(a, b) { return a - b; }

//apply
var a1 = sub.apply(add, [4, 2]);
var a2= add.apply(sub, [4, 2]); //call
var a1 = sub.call(add, 4, 2); var a2= add.call(sub, 4, 2); //输出:a1=2 a2=6