find context 区别:
刚学习 jQuery 的朋友可能还不知道在 jQuery 选择器中可以指定上下文对象,以前在 jQuery插件的写法文章中就有人问过 context 是什么意思。今天就看看 context,掌握后灵活使用可提高代码质量。
<div class="picture">
<img src="img.jpg" />
</div>
如查看 class 为 picture 的 img,通常情况下我们会使用 find 方法来查找,也许你也有兴趣看看 find() children区别。
var $img = $('.picture').find('img');
我们也可以指定上下文对象,如下:
var $img = $('img', '.picture');
经过测试发现前者在性能上比后者还稍微快些,查看 jQuery 源码可发现后者会转成find 方法,在转换时要花点时间。但当我们封装一个常用的方法时,使用 context 会比较合适,如下:
reSize = function (div) {
$('img', div).width(100);
$(div).find('img').width(100);
}
在这种情况下比较 jQuery find 方法和 context,可以看出合理使用 context 会提高我们的代码质量。
find children区别
find() children()这两个方法也是比较相似的,本篇看下它们两个的区别。find()查找的是子孙、children()查找的是子女元素,相信你如果对dom结构熟悉的话,已经能区分它们两者的不同了。
接下来,直接看个具体的例子,好让你一下子掌握find()和children()的区别。html如下:
<div id="showfind" style="width:200px;">
<div>
jQuery学习
<div style="background:blue;">find要起作用</div>
</div>
<div>jQuery学习</div>
</div>
$("#showfind").find("div").css("background", "yellow");
$("#showfind ").children("div").css("background", "yellow")
前者,返回结果如图1,后者,返回结果如图2:
图1 图2
简单的说,find会找当前div下的所有元素,而children只会找当前div下的一层,不会再向下查找。本篇总结了find()方法和children()方法的区别,最后我们发现常用的、安全些的方法是find()。
浙公网安备 33010602011771号