简体   繁体   中英

jquery- onclick find element with same class

I'm stuck. I have two sets of dynamic elements with a common class ( zone and box ) and a dynamic class:

<span class="zone dynamicClass1 clickable">Text</span>
<span class="zone dynamicClass6-2 clickable">Text</span>

<div class="box dynamicClass6-2"></div>
<div class="box dynamicClass1"></div>

When you mouseover the <span> "zone" , I want to add a class to the <div> "box" . Then on mouseleave I want the class to be removed. Thus, something like:

$(document).on("mouseenter",".zone",function(){
    $(this + ".the dynamic class").find(".box.the same dynamic class").addClass("hovered");
}).on("mouseleave",".zone",function(){
    $(".box.the found dynamic class").removeClass("hovered");
});

The dynamic classes have to be retrieved from the hovered element and then used in finding its match, they cannot be programmed by name. Any help would be great.

The way you have it setup right now, you search for the div inside the span. What you want to do is get the class and then find the according div. I would suggest moving the common class to either an id data attribute, so you can do this:

<span class="zone clickable" id="dynamicClass1">Text</span>
<span class="zone clickable" id="dynamicClass6-2" >Text</span>

var currentClass = $(this).attr("id");
$("div." + currentClass).addClass("hovered");

or this:

<span class="zone clickable" data-class="dynamicClass1">Text</span>
<span class="zone clickable" data-class="dynamicClass6-2" >Text</span>

var currentClass = $(this).data("class");
$("div." + currentClass).addClass("hovered");

See this JSFiddle: http://jsfiddle.net/7v3hd/1/

DEMO

$(document).on("mouseenter",".zone",function(){
    var $that   = $(this),
        classes = $that.attr('class'),

        // this is the meat here
        // you need to do a string manipulation
        // to get the dynamic class out of the
        // class attribute. You could also do this
        // with regex, or split.
        theDynamicClass = classes.replace('zone', '').replace('clickable', '').trim(),
        $boxWithSameClass = $(".box."+theDynamicClass);

    $boxWithSameClass.addClass("hovered");
    $that.one("mouseleave",function(){
        $boxWithSameClass.removeClass("hovered");
    });
});

You can use;

$(document).on("mouseenter",".zone",function(){
    var classes = $(this).attr("class").split(" ");

    $("div." + classes[1]).addClass("hovered");
}).on("mouseleave",".zone",function(){
    var classes = $(this).attr("class").split(" ");
    $("div." + classes[1]).removeClass("hovered");
});

HEre is a working demo: jsfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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