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

时间:2022-10-19 20:37:58

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. cant I do something along these lines:

但我也想对名为tabs的div应用相同的效果,而不重复相同的代码。我能做点什么吗?

$("#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. I think I am just getting the jQuery syntax wrong, still sorta new to jQuery

问题是,上面的问题只适用于“选项卡”div,而工具栏停止工作。我认为我只是弄错了jQuery语法,仍然是jQuery的新手

3 个解决方案

#1


5  

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. It says "apply this to any img tags that are in a parent element with the id of toolbar". E.g.:

'#toolbar img'是整个选择器。它说:“将此应用于带有工具栏id的父元素中的任何img标记”。例如:

<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选择器相同,因此对于更多的信息研究来说。

#2


1  

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

尝试$(“#工具栏img, #tabs img”)。

#3


1  

Shouldn't there be "#toolbar img, #tabs" instead of "#toolbar, #tabs img" ?

难道不应该有“#工具栏img, #tabs”而不是“#toolbar, #tabs img”吗?

#1


5  

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. It says "apply this to any img tags that are in a parent element with the id of toolbar". E.g.:

'#toolbar img'是整个选择器。它说:“将此应用于带有工具栏id的父元素中的任何img标记”。例如:

<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选择器相同,因此对于更多的信息研究来说。

#2


1  

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

尝试$(“#工具栏img, #tabs img”)。

#3


1  

Shouldn't there be "#toolbar img, #tabs" instead of "#toolbar, #tabs img" ?

难道不应该有“#工具栏img, #tabs”而不是“#toolbar, #tabs img”吗?