jquery - 为什么我不能在 $.each 函数中使用 `this` 作为 jQuery 函数的字符串参数

标签 jquery each

我正在努力处理我正在处理的一些 jQuery 代码,我已将问题缩小到这个简单的示例,但它的行为也不像我预期的那样:

jsFiddle: http://jsfiddle.net/HypYT/

<小时/>

HTML

<div id="a">a: <span>A</span></div>
<div id="b">b: <span>B</span></div>​

jQuery

jQuery.each( ["#a", "#b"], function(){
    alert(this);    // alerts "#a" and "#b"
    $(this).hide(); //not working
    $('#b').hide(); //working
});​
<小时/>

有人知道这里发生了什么吗?

最佳答案

如果在字符串(或其他原语)上调用函数,this 将成为装箱对象。
因此,typeof this 将返回“object”,而不是“string”
这破坏了 jQuery。 (没有双关语)

您可以通过将其强制返回字符串基元来解决此问题:

$(String(this)).hide()

您可以通过编写来修复任意基元的此问题

var self = this.constructor(this);

但是,使用传递给 .each() 的第二个参数会更快,因为它首先会避免装箱。

关于jquery - 为什么我不能在 $.each 函数中使用 `this` 作为 jQuery 函数的字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12497837/

相关文章:

jquery - 获取输入字段的标签

jquery - $(this) 和 $ ("#id") 之间有什么区别?

javascript - 0x800a138f - Internet Explorer : JavaScript runtime error: Unable to get property '0' of undefined or null reference

jquery - 如何在jquery插件中正确实现option/update方法?

jquery 数组返回一个未定义的?

jquery - 删除组内元素的类以进行同位素过滤

html - .each 在 HTML Slim 中做其他声明

javascript - 如何多次使用时间选择器

加载另一个页面后 JavaScript 继续

javascript - 替换变量中的字符