jQuery在鼠标悬停时将目标ID与类相同

时间:2014-10-20 12:55:13

标签: jquery

我试图在#photo-menu li上鼠标悬停时将活动课程添加到#photo-desc li。

$('#photo-menu li').on('mouseenter mouseleave', function(){
        var pClass = this.className;
        var pId = ('#photo-desc li').id;
        if (pClass == pId) {$('#photo-desc li').addClass('active');}
   });

<ul id="photo-menu">
    <li class="photo-1"><a href="">Photo 1</a></li>
    <li class="photo-2"><a href="">Photo 2</a></li>
    <li class="photo-3"><a href="">Photo 3</a></li>
    <li class="photo-4"><a href="">Photo 4</a></li>
</ul>

<ul id="photo-desc">
    <li id="photo-1">Photo 1</li>
    <li id="photo-2">Photo 2</li>
    <li id="photo-3">Photo 3</li>
    <li id="photo-4">Photo 4</li>
</ul>

4 个答案:

答案 0 :(得分:4)

在您的示例中,您的类具有与您的第二个ID相同的名称。所以非常简单:

$('#photo-menu li').on('mouseenter mouseleave', function (e) {
    var curClass = $(this).attr("class"); //take class
    if (e.type == "mouseenter") {
        $("#" + curClass).addClass("active"); //use class name to get the id in second list
    } else {
        $("#" + curClass).removeClass("active");
    }
});
.active {
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="photo-menu">
    <li class="photo-1"><a href="">Photo 1</a>

    </li>
    <li class="photo-2"><a href="">Photo 2</a>

    </li>
    <li class="photo-3"><a href="">Photo 3</a>

    </li>
    <li class="photo-4"><a href="">Photo 4</a>

    </li>
</ul>
<ul id="photo-desc">
    <li id="photo-1">Photo 1</li>
    <li id="photo-2">Photo 2</li>
    <li id="photo-3">Photo 3</li>
    <li id="photo-4">Photo 4</li>
</ul>

答案 1 :(得分:0)

只需将该类添加到元素(ById),就像这样简单:

$('#photo-menu li').on('mouseenter', function(){
        var class = $(this).attr('class');
        var pId = $('#'+class).addClass('active');}
});


$('#photo-menu li').on('mouseleave', function(){
        var class = $(this).attr('class');
        var pId = $('#'+class).removeClass('active');}
});

答案 2 :(得分:0)

我不知道你想对var pId = ('#photo-desc li').id;做什么,但我也建议使用jQuery.hover。在那里,您可以使用.addClass("active")在鼠标悬停时设置活动课程,并使用each(function() {$( this ).removeClass("active");});您可以在鼠标移除时从所有div中删除它。

请参阅小提琴http://jsfiddle.net/gfobe/owvwrufo/1/作为示例解决方案。

答案 3 :(得分:0)

FIDDLE

jQuery hover本身附加了两个处理程序: -

  • 的mouseenter
  • 鼠标离开

The .hover() method binds handlers for both mouseenter and mouseleave events. You can use it to simply apply behavior to an element during the time the mouse is within the element.

我仍然希望使用hover handlers来回答这个问题。

 $('#photo-menu li').on('mouseenter', function () {
    var pClass = $(this).attr('class');

    $('#photo-desc li').each(function () {
      var pId = $(this).attr('id');

      if (pClass == pId) {
        $(this).addClass('active');   
        return;       
       }
    });
 }).on('mouseleave',function(){
        $('li.active').removeClass('active');
    });