jQuery 选择器问题

标签 jquery jquery-selectors

我有一个关于 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/

相关文章:

javascript - jQuery - 选择属性名称(不是值)以...开头的所有元素?

jquery - 从右到左调整jquery中的div

jquery - jQuery 的元素或类 LIKE 选择器?

asp.net 中的 jQuery UI 对话框和 Ajax POST

javascript - 上传文件时使用 JavaScript 确定文件类型

javascript - 奇怪的 AJAX 错误 : not getting a response on AJAX call while getting a response when doing the exact call with different values

jquery - Modernizr/yepnope 执行顺序 WRT jQuery + 插件故障排除

jquery - PHPStorm IDE 中低效的 jQuery 使用警告

jquery - 禁用网页上的选择,但不能在表单上禁用选择,否则人们无法通过鼠标选择输入字段

php - 运行单行 javascript 代码?