简体   繁体   English

使用此和变量的多个选择器

[英]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. 单击时,jQuery抓取数据幻灯片并使用该信息查找匹配的ID并应用一个类。

<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时,“ target”没有将活动类应用于它。

$(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: 您可以使用add()方法实现这一点:

$(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 但它不会找到它,因为目标不包含该元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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