【问题标题】:Why does jQuery class selector only return one element?为什么jQuery类选择器只返回一个元素?
【发布时间】:2017-11-29 21:32:33
【问题描述】:

文档中有多个带有类的div。

如控制台中所见,document.getElementsByClassName 产生:

document.getElementsByClassName('current-pad-o')
HTMLCollection (2) = $8
0 <div class="red current-pad-o"> first value </div>
1 <div class="red current-pad-o"> second value </div>

和jquery,使用相同的类选择器产生:

$('.current-pad-o')
// (the first div only - no collection)
<div class="red current-pad-o"> first value </div>

我希望 jquery 语句也有一个集合。这些都是在 Safari 和 Firefox 中输出的。

根据jQuery Class Selector documentation,第二个选择器选择给定类的所有元素

为什么 jquery 只返回一个,而不是一个集合?

【问题讨论】:

  • 似乎document.getElementsByClassName 返回了错误的东西!!第二个 div 不包括 current-pad-o
  • 我敢打赌它不是 jQuery,我敢打赌你认为 jQuery 是 document.querySelector 的调试器的快捷方式
  • 但这不是同一个类选择器——一个是current-pad-o,另一个是currtrip-pad-o。它们是不同的。
  • 问题已编辑。 jQuery 选择器适用于更新后的示例。
  • 请提供重现问题的minimal reproducible example

标签: javascript jquery jquery-selectors


【解决方案1】:

您没有 jQuery,您使用的是调试器的快捷方式 document.querySelector()。如果你使用$$('.current-pad-o'),你会得到所有这些。

验证你没有使用 jQuery,在命令行中输入以下内容:

console.log($)

对于 querySelector,您将看到:

function $(selector, [startNode]) { [Command Line API] }

对于 jQuery,你会看到:

function (a,b){return new n.fn.init(a,b)}

参考:console expressions

【讨论】:

  • 当一个人“假设”时会发生这种情况。你击中了要害。 console.log($) = undefined
  • 是的,它是未定义的,但你可以在控制台上输入 $,如果 jquery 不存在,它将显示为“本机代码”。
猜你喜欢
  • 2012-03-29
  • 1970-01-01
  • 2021-05-13
  • 2011-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多