当涉及到“this”时,jQuery 的层次结构如何工作?选择器?
例如,如果我要使用此代码:
$(".Class").children(:last).click(function(){
$(this).siblings(":not(:last)").toggle();
}
“this”会引用“.Class”类,还是会引用指定“.Class”类的最后一个子类?
For example, if I were to use this code:
$(".Class").children(:last).click(function(){
$(this).siblings(":not(:last)").toggle();
}
Would "this" refer to the ".Class" class, or would it refer to the last child of the specified ".Class" class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
this
指的是在触发事件的链中最终选择器中匹配结果的 DOM 元素;在本例中,为的
:last
子级。类。因此,如果您单击最后一个.Class
类的last
子级,该事件就会触发。在此 fiddle 中查看如何仅foo2
触发警报。除此之外,它不会像您发布的那样工作,因为
:last
应该作为字符串放在引号中。this
would refer to the DOM element that results matched in the final selector in the chain that triggers the event; in this case, the:last
child of.Class
. So, the event would trigger if you click thelast
child of the last.Class
class. See in this fiddle how onlyfoo2
triggers the alert.Except, it won't work as you've posted it, since
:last
should be in quotes as a string.它将引用单击的元素。也就是说,绑定事件侦听器时类为
Class
的元素中的最后一个元素。如果在事件监听器已经绑定后,您在同一父级中的前一个最后一个元素之后添加了另一个元素,那么它仍然会监听之前最后一个元素,以及this
也将是上一个最后一个。It would refer to the element clicked. That is, the last element in the element with a class of
Class
at the time the event listener was bound. If you added another element after the previous last element in the same parent after the event listener was already bound, it would still be listening to what was previously the last one, andthis
will also be the previous last one.我认为这是这种情况下的最后一个孩子。它始终是点击词之前匹配的最后一个元素。
I think that it is the last child in that case. It is always the last element matching before the click word.
它指的是您正在操作的当前上下文。在您提供的示例中,它将指的是指定“Class”类的最后一个子级。
如果您要执行以下操作:
$(this)
将在迭代时引用每个子项。It refers to the current context you're operating in. In the example you provided it would refer to the last child of the specified "Class" class.
If you were to do the following:
$(this)
would refer to each child as it gets iterated over.