jquery悬停多个项目

时间:2010-11-23 23:29:20

标签: jquery

说你有这个代码:

    $("#sub_nav_home1").hover(function () {
        $("#homepage").removeClass();
        $("#homepage").addClass("homepage1");
    });
    $("#sub_nav_home2").hover(function () {
        $("#homepage").removeClass();
        $("#homepage").addClass("homepage2");
    });
    $("#sub_nav_home3").hover(function () {
        $("#homepage").removeClass();
        $("#bhomepage").addClass("bhomepage3");
    });

    <ul class="nav sub_nav_home">
        <li id="sub_nav_home1"><a href="#"><span>LINK1</span></a></li>
        <li id="sub_nav_home2"><a href="#"><span>LINK2</span></a></li>
        <li id="sub_nav_home3"><a href="#"><span>LINK3</span></a></li>
     </ul>

有没有办法我们只能做一次悬停jquery功能,而不是每个链接一个?

希望有意义

干杯

2 个答案:

答案 0 :(得分:1)

呃,我能想到的最快的方式是(这也是动态的):

    $("#sub_nav_home a").hover(function () {
         $("#homepage").removeClass().addClass("homepage"+$(this).parent().attr('id').split('sub_nav_home')[1]);
    });

    <ul class="nav sub_nav_home">
        <li id="sub_nav_home1"><a href="#"><span>LINK1</span></a></li>
        <li id="sub_nav_home2"><a href="#"><span>LINK2</span></a></li>
        <li id="sub_nav_home3"><a href="#"><span>LINK3</span></a></li>
     </ul>

这将使课程主页[该父母内部的身份证号码]即主页1,主页2等

- UPDATE -

这应该适合你(但我没有测试它!如果它不起作用,请告诉我)

//find the first li and add a class of current to start the loop
$('.sub_nav_home li:first').addClass('current');
//Here we set the loop
setInterval(function(){
    //Here we are checking if there IS a next item. If there IS it'll return 1
    //which will make this if() true (1 > 0)
    if($('.current').next().length > 0){
        //Here we grab the current .current, remove the class, get the next item
        //and then add .current to that
        $('.current').removeClass('current').next().addClass('current');
    }
    else{
        //If the if() fails (returns 0 [no next() item]) we'll get the current
        //.current, remove the class, get the parent, find the first item in the
        //parent (first <li> of the <ul>) and add a class of current
        $('.current').removeClass('current').parent().find(':first').addClass('current');
    }
},3000) //3000 = 3 seconds

P.S。如果这适合你,请务必给我一个投票;)

答案 1 :(得分:0)

为每个li添加课程:

<li class="c1" id="sub_nav_home1"><a href="#"><span>LINK1</span></a></li>

$('ul.nav sub_nav_home li').hover(function () { 
        $("#homepage").removeClass(); 
        $("#bhomepage").addClass("bhomepage" + this.className.replace("c","")); 
    });