我有一个关于 jQuery 选择器的简单问题。
正在这样做:
$('.class_el_1, .class_el_2').hide();
与使用 jQuery 的 .each 函数循环遍历每个元素相同吗?
最佳答案
它具有将它们全部隐藏的相同效果,但内部并不完全相同,不是。 .each()
接受一个回调,其中 this
可用于对每个元素执行特定操作,因此它会做更多的工作。 .hide()
在链中只需在元素上设置 display: none;
(存储它们以前的值)。
You can see how it works internally here ,对于不带参数的调用:
for ( var i = 0, l = this.length; i < l; i++ ) {
var old = jQuery.data(this[i], "olddisplay");
if ( !old && old !== "none" ) {
jQuery.data( this[i], "olddisplay", jQuery.css( this[i], "display" ) );
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( var j = 0, k = this.length; j < k; j++ ) {
this[j].style.display = "none";
}
上面的this
指的是$('.class_el_1, .class_el_2')
匹配的元素集,只是使用for
循环来读取它们。
关于jQuery 选择器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3839593/