“i”和“this”的顺序很重要。第一个,图标添加在按钮后面。第二个,图标添加在按钮之前。这是为什么?
示例1:
$('.btn').click(function(){
$('i', this).removeClass().addClass("icon-down");
})
示例2:
$('.btn').click(function(){
$(this, 'i').removeClass().addClass("icon-down");
})
最佳答案
很明显,您使用的这两种形式将产生不同的结果。
$('i', this)
此表单将找到任何<i>
this
所指向元素的子元素。它在结构上相当于$(this).find('i')
这是我更喜欢的编写方式,因为我认为它更具可读性。
在 jQuery 文档中,此表单被记录为 jQuery( selector [, context ] )
.
您的其他表格:
$(this, 'i')
并不是 jQuery 函数真正直接支持的选项,因为没有记录的选项采用 (element, string)
。我将检查 jQuery 代码,但这很可能只会被解释为 $(element)
形式,因此将是 $(this)
第二个参数被忽略。此选项记录为 jQuery( element )
。如果第一个参数是 DOM 元素,则忽略第二个参数。
所以,第一个选项找到子 <i>
元素。第二个选项仅作用于按钮本身。
编辑:在查看 jQuery 源代码时,我已经验证了 $(this, 'i')
与 $(this)
的处理方式相同。事实上,这就是 jQuery 函数的操作部分:
init: function( selector, context, rootjQuery ) {
if ( typeof selector === "string" ) {
// handle selector string here
// ...
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
关于jQuery 多个选择器顺序为 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30249088/