简体   繁体   中英

Multiple selectors using this and variable

I created a quick tab section on a website. On click, jQuery grabs the data-slide and uses that info to find a matching ID and applies a class.

<div class="service-link" data-slide="#post-123">Click Me</div>

'target' does not get the active class applied to it when I use 'this' and target on the same line.

$(this, target).addClass("active");

It works if I use two lines. Anybody know why I cant use one line?

$(this).addClass("active");
$(target).addClass("active");

Full Working Script -

$(".service-link").click(function(){
    var target = $(this).data("slide");
    $(".service-type-slide, .service-link").removeClass("active");
    $(target).addClass("active");
    $(this).addClass("active");
})`

You could use the add() method to achieve this:

$(this).add(target).addClass("active");

Example Here


You were trying:

$(this, target).addClass("active");

which is basically equivalent to using:

$(target).find(this).addClass("active");

That's why it wasn't working.

You can see an example demonstrating this here .

I think that:

   $(this, target)

will try to find the node element (which this refer to) inside the target context. but it wont find it, because target does not contains that element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM