jquery- onclick查找具有相同类的元素

时间:2014-03-25 15:15:05

标签: javascript jquery

我被困住了。我有两组带有公共类(zonebox)的动态元素和一个动态类:

<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>

当您将鼠标悬停在<span> "zone"上时,我想向<div> "box"添加一个课程。然后在mouseleave上我希望删除该类。因此,像:

$(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");
});

动态类必须从悬停元素中检索,然后用于查找匹配,它们不能按名称编程。任何帮助都会很棒。

3 个答案:

答案 0 :(得分:2)

您现在设置它的方式,您搜索范围内的div。你想要做的是获得课程,然后找到相应的div。我建议将公共类移动到id数据属性,这样你就可以这样做:

<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");

或者这个:

<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");

请参阅此JSFiddle: http://jsfiddle.net/7v3hd/1/

答案 1 :(得分:2)

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");
    });
});

答案 2 :(得分:1)

你可以使用;

$(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是一个有效的演示: jsfiddle