开发者

How does jQuery's hierarchy work when it comes to the "this" selector?

开发者 https://www.devze.com 2023-04-12 07:23 出处:网络
For example, if I were to use this code: $(\".Class\").children(:last).click(function(){ $(this).siblings(\":not(:last)\").toggle();

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开发者_Go百科 last child of the specified ".Class" class?


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.


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号