开发者

Adding CSS Class using jQuery

Below I have i开发者_StackOverflowncluded the jquery code I am using to add a css class to the link in the side column that equals the active url, but it's not working, and at some point it did.

Link: http://www.liquidcomma.com/portfolio/project/TSF_Robot_Ad/1/

<script type="text/javascript">
$(document).ready(function(){
      $("ul.right_submenu > li > a").each(function() {
            if ($(this).attr("href") == location.href)
            {
                  $(this).addClass("CurrentProject");
            });
};
</script>


Well, besides that code missing braces and parens it can be done much simpler:

$(function(){
    $("a[href^='" + location.href + "']").addClass("CurrentProject");
});


You have unclosed braces in your script:

$(document).ready(function(){
    $("ul.right_submenu > li > a").each(function() {
        var a = $(this);
        if (a.attr('href') == location.href) {
            a.addClass("CurrentProject");
        }
    });
});

and you could rewrite your script like this:

$('ul.right_submenu > li > a[href=' + location.href + ']')
    .addClass('CurrentProject');


Following your link, my location.href goes to http://www.liquidcomma.com/portfolio/project/TSF_Robot_Ad/1/ but your project link in the page points to http://www.liquidcomma.com/portfolio/project/trade_show_fabrications/1... that will make attr('href') != location.href.

In the other links, location.href will be ending with a slash whereas the link's href will not.

You should use something else to match your project other than the href attribute, if you expect it to change in the future (and it probably will).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜