开发者

Using jQuery, how do I select all instances of a class, when using a multiple class selector

I have a set of classes that are used multiple times on a page that I would like to add hover event handlers to, so that when one instance of the c开发者_C百科lass is hovered over, all instances will display a a "glow" affect.

I would like to avoid having to write out 10+ functions, so I have been trying to get it to work using jQuery's multiple selector API. e.g.

$(".r1,.r2,.r3,.r4,.r5,.r6,.r7,.r8,.r9,.r10").hover(
    function () {
        $(this).addClass("glow"); //All of r1, or r2 etc
    },
    function () {
        $(this).removeClass("glow"); //All of r1, or r2 etc
    }
);

My problem being that I can't figure out how to select all instances of the class, rather then just: $(this).

Help much appreciated


Use the filter()[docs] method to filter the entire collection based on the className property of the element that received the event.

var r_classes = $(".r1,.r2,.r3,.r4,.r5,.r6,.r7,.r8,.r9,.r10"),
    hovered;

r_classes.hover(
    function () {
        hovered = r_classes.filter( '.' + this.className ).addClass("glow"); 
    },
    function () {
        hovered.removeClass("glow"); //All of r1, or r2 etc
    }
);

When filtered, the filtered set is assigned to the hovered variable. This is so you don't need to repeat the filter.

Also, this assumes that the r1,r2,...rn class is the only one initially assigned to the element (before the glow class is added).


EDIT:

Live Example: http://jsfiddle.net/pvQes/1/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜