怎么用变量说:如果这个id匹配这个类不要这样做

时间:2010-08-28 03:50:46

标签: javascript jquery

用语言来说,我想说,如果正文ID不等于列表项的类,则执行以下函数,我试图使代码正确,但似乎没有任何效果。

我有4个页面,每个页面都有一个ID,以使活动状态在css精灵中工作,效果很好。最重要的是我在正常和悬停之间添加了jquery不透明效果,但问题是当我悬停活动状态时它也会变为悬停,我希望活动精灵在悬停时保持不变,任何帮助都会受到赞赏,Saludos。< / p>

Html:

<ul id="nav">
    <li class="home"><a href="index.html" title="Home Page">Home</a></li>
    <li class="portfolio"><a href="portfolio.html" title="Portfolio Page">Portfolio</a></li>
    <li class="contact"><a href="contact.html" title="Contact Form Page">Contact</a></li>
    <li class="about"><a href="about.html" title="About me Page">About me</a></li>
    </ul>

Jquery的:

  $(document).ready(function(){

    // Get the ID of the body
    var parentID = $("body").attr("id");

    // Loop through the nav list items
        $("#nav li").each(function() {

        // compare IDs of the body and class of list-items
           var myClass = $(this).attr("class");

        // only perform the change on hover if the IDs don't match (so the active link doesn't change on hover)
        if (myClass != "n-" + parentID) {

   // Opacity effect between states 
    $('ul#nav li a').removeClass('hover');  
    $("ul#nav li a").wrapInner("<span></span>");
    $("ul#nav li a span").css({"opacity" : 0});
    $("ul#nav li a").hover(function(){
        $(this).children("span").stop().animate({"opacity" : 1}, 500);
    }, function(){
        $(this).children("span").stop().animate({"opacity" : 0}, 500);
        });
      }

     });

});

1 个答案:

答案 0 :(得分:1)

我不确定您为什么要检查其课程不是'n - <li>'的parentId。难道你不只是想要那些类与相同而不是身体ID的人吗?

限制<li>选择器仅排除您不想要的课程:

$(document).ready(function(){
    // Get the ID of the body
    var parentId = $("body").attr("id");

    // Loop through the nav list items
    $("#nav li[class!=" + parentId + "]").each(function(){
        // Opacity effect between states 
        $('ul#nav li a').removeClass('hover');  
        $("ul#nav li a").wrapInner("<span></span>");
        $("ul#nav li a span").css({"opacity" : 0});
        $("ul#nav li a").hover(function(){
            $(this).children("span").stop().animate({"opacity" : 1}, 500);
        }, function(){
            $(this).children("span").stop().animate({"opacity" : 0}, 500);
        });
    });
});