admin管理员组

文章数量:1384270

I am using the following code to apply a hover effect to a set of images within a div called toolbar:

$("#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:

$("#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

I am using the following code to apply a hover effect to a set of images within a div called toolbar:

$("#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:

$("#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

Share Improve this question edited Sep 21, 2009 at 15:47 Neil N asked Jul 7, 2009 at 22:28 Neil NNeil N 25.3k17 gold badges87 silver badges147 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

You separate multiple selectors by mas 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.:

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

#tabs img, is a whole other selector.

These are the same syntax as CSS selectors, so for more information research that.

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

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

本文标签: javascriptHow do I use multiple selectors in jQueryStack Overflow