【问题标题】:jQuery id selector not returning empty array for non-existant element?jQuery id 选择器不为不存在的元素返回空数组?
【发布时间】:2013-04-21 18:54:03
【问题描述】:

我看到一个 jQuery id 选择器为一个应该不存在的元素返回一个数组项。

$('#bootstrap_alert_placeholder') 在我的函数中返回,(来自 Chrome 控制台)

[context: document, selector: "#bootstrap_alert_placeholder", jquery: "1.9.1", constructor: function, init: function…]

但是当我在控制台中调用选择器来仔细检查输出时,我看到一个空数组,这正是我所期望的。

有人知道这里发生了什么吗?我希望该函数在不同的 this 上下文中执行,但我不知道这会如何影响选择器的结果。

【问题讨论】:

  • 好吧呃,不知道有什么问题。
  • 所有这些属性都存在于一个 jQuery 对象上;空的或非空的; length 属性显示什么?
  • 类数组对象的 Chrome 控制台输出令人困惑。该事物不包含任何项目,具有length: 0 但还有一些其他属性(其中大部分继承自$.fn

标签: javascript jquery jquery-selectors


【解决方案1】:

在控制台中尝试这个,在这个页面上:

console.log($("#blah"));
//possible output in chrome: 
//[context: document, selector: "#blah_im_not_a_real_element", 
//constructor: function, init: function, selector: ""…]

//or in firefox: ({context:({}), selector:"#blah"})


 console.log($("#blah_im_not_a_real_element").length)
//outputs 0

jQuery 对象不是像nullundefined 中的“空”。它是空的,长度为 0,但仍然是一个 jQuery 对象

console.log($("#blah_im_not_a_real_element").constructor)

【讨论】:

  • 啊,就是这样,只是Chrome的控制台在这种情况下令人困惑。谢谢。
猜你喜欢
  • 2022-10-02
  • 2023-03-17
  • 2012-03-29
  • 2012-04-27
  • 2012-10-29
  • 2019-03-19
  • 2023-03-20
  • 2012-09-18
  • 2011-10-23
相关资源
最近更新 更多