简体   繁体   English

如何在jQuery中使用多个选择器?

[英]How do I use multiple selectors in jQuery?

I am using the following code to apply a hover effect to a set of images within a div called toolbar: 我正在使用以下代码将悬停效果应用于称为工具栏的div中的一组图像:

$("#toolbar img").hover(
    function()
    {
        this.src = this.src.replace("_off", "_on");
    },
    function()
    {
        this.src = this.src.replace("_on", "_off");
    }
);

But I also want to apply the same effect to a div called tabs without repeating the same code. 但我也想将相同的效果应用于称为tabs的div,而无需重复相同的代码。 cant I do something along these lines: 我不能按照以下方式做一些事情:

$("#toolbar, #tabs img").hover(
    function()
    {
        this.src = this.src.replace("_off", "_on");
    },
    function()
    {
        this.src = this.src.replace("_on", "_off");
    }
);

The problem is the above only applies to the "tabs" div, while the toolbar stops working. 问题是以上内容仅适用于“选项卡” div,而工具栏却停止了工作。 I think I am just getting the jQuery syntax wrong, still sorta new to jQuery 我想我只是弄错了jQuery语法,仍然是jQuery的新手

You separate multiple selectors by commas as you did. 您可以像以前一样用逗号分隔多个选择器。 If you want to recreate the effect as it was in the first example it needs to be: 如果要像在第一个示例中那样重新创建效果,则需要:

$("#toolbar img, #tabs img")

'#toolbar img' is the entire selector. '#toolbar img'是整个选择器。 It says "apply this to any img tags that are in a parent element with the id of toolbar". 它说:“将其应用于带有工具栏ID的父元素中的所有img标签”。 Eg: 例如:

<div id ="toolbar">
   <img .../>
   <img .../>
</div>

#tabs img, is a whole other selector. #tabs img,是另一个选择器。

These are the same syntax as CSS selectors, so for more information research that. 这些语法与CSS选择器的语法相同,因此可以进行更多信息研究。

尝试$("#toolbar img, #tabs img")

应该没有“ #toolbar img,#tabs”而不是“ #toolbar,#tabs img”吗?

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

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