2014-10-20 46 views
1

我想在#photo-desc li上添加活動類,當鼠標懸停在#photo-menu li上時。jQuery目標與鼠標上的類相同的編號

$('#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> 
+0

製作小提琴,告訴我們 – Innodel 2014-10-20 12:56:42

+0

@ ask4tec有什麼不對,我的答案是不適合你的要求是什麼? – 2014-10-21 06:53:46

回答

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>

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');} 
}); 
0

我不明白你想用var pId = ('#photo-desc li').id;做什麼,但我也對電子書籍使用jQuery.hover這一點。您可以使用.addClass("active")在鼠標懸停上設置活動類,並使用each(function() {$(this).removeClass("active");});您可以在所有div的鼠標移除它。

查看小提琴http://jsfiddle.net/gfobe/owvwrufo/1/作爲示例解決方案。

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