当涉及到“this”时,jQuery 的层次结构如何工作?选择器?

发布于 2024-12-09 04:28:09 字数 193 浏览 1 评论 0原文

例如,如果我要使用此代码:

$(".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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

相守太难 2024-12-16 04:28:09

this 指的是在触发事件的链中最终选择器中匹配结果的 DOM 元素;在本例中,为 :last 子级。类。因此,如果您单击最后一个 .Class 类的 last 子级,该事件就会触发。在此 fiddle 中查看如何仅 foo2 触发警报。

<div class="Class">
    <div> </div>
    <div> </div>
    <div> </div>
   <div> </div> <!--This is the last child of .Class-->

</div>

除此之外,它不会像您发布的那样工作,因为 :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 the last child of the last .Class class. See in this fiddle how only foo2 triggers the alert.

<div class="Class">
    <div> </div>
    <div> </div>
    <div> </div>
   <div> </div> <!--This is the last child of .Class-->

</div>

Except, it won't work as you've posted it, since :last should be in quotes as a string.

依 靠 2024-12-16 04:28:09

它将引用单击的元素。也就是说,绑定事件侦听器时类为 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, and this will also be the previous last one.

伴我心暖 2024-12-16 04:28:09

我认为这是这种情况下的最后一个孩子。它始终是点击词之前匹配的最后一个元素。

I think that it is the last child in that case. It is always the last element matching before the click word.

请帮我爱他 2024-12-16 04:28:09

它指的是您正在操作的当前上下文。在您提供的示例中,它将指的是指定“Class”类的最后一个子级。

如果您要执行以下操作:

$(".Class").children().each(function(){
    ...
});

$(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:

$(".Class").children().each(function(){
    ...
});

$(this) would refer to each child as it gets iterated over.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文