Is it possible to select $(this) AND use selectors

2019-04-04 16:42发布

问题:

I'm wondering if I can use $(this) as well as a class selector before running a function on them.

So rather than doing;

$(this).toggleClass('open');
$('.closed').toggleClass('open');

Do something more like;

$(this, '.closed').toggleClass('open');

Whereas really, the above will select 'this' within the context of '.closed'

Regards,

回答1:

You can use add():

$(".closed").add(this).toggleClass("open");

It will add this element to the set of matched elements (i.e. .closed).