Hover an element, add class to another
I have two lists:
<ul id="list1">
<li class="link1">Link 1</li>
<li class="link2">Link 2</li>
<li class="link3">Link 3</li>
</ul>
<ul id="list2">
<li class="link1">Link 1</li>
<li class="link2">Link 2</li>
<li class="link3">Link 3</li>
</ul>
I want when I hover "link1" from "list1" to add a class (.active) to "link1" from "list2". And same开发者_Python百科 for "list2"... It is possible to make a function, because I have lot of li with same classes, and will be too bad to do it manually for each.
Try this:
$("#list1 li,#list2 li").hover(function() {
var index = $(this).index();
$("#list1, #list2").each(function() {
$("li",this).eq(index).toggleClass("active");
});
});
jsFiddle
If your li elements does not have another class than link1, link2 etc. it pretty easy:
var list1 = $("#list1"); // Store references to list1 and list2
var list2 = $("#list2");
list1.find("li").hover(function() {
var className = $(this).attr("class"); // Fetch current class name
list2.find("li").removeClass("active"); // Remove active class from all items in list2
list2.find("." + className).addClass("active"); // Find an item with the same class name, but only items thats children of list2 (second parameter), and add class active
});
Something like:
$("#list1 .link1").hover(function () {
$("#list2 .link1").addClass("active");
});
or, use $("#list2").find(".link1")...
Try something like this:
$("li").hover(function () {
var targetClass = $(this).attr('class');
$("."+targetClass).not($(this)).addClass("active");
}, function() {
$("li").removeClass("active");
});
You can do this even if they don't have the same class
using $(this).index()
will return the index of current hovered element. So, you just have to add the class to element of same index on the other list
Here's a basic working example:
http://jsfiddle.net/Wckyq/
精彩评论