jquery addClass函数的问题

时间:2011-05-15 23:02:42

标签: jquery addclass

<script>    
$("ul#sol_menu li a").addClass(function()) {
var current_page = document.location.href;
if ($(this).attr.("href").match(current_page)) {
$(this).addClass('highlight');
};
});
</script>

这有什么问题?

2 个答案:

答案 0 :(得分:5)

我相信这可能就是你想要的...... 正如SLaks指出的那样,你的语法(在这种情况下)有点残忍......

<script>    
    $(document).ready(function(){
        var current_page = document.location.href;
        $("ul#sol_menu li a").each(function(){
            if ($(this).attr('href') == current_page) {
                $(this).addClass('highlight');
            }
        });
    });
</script>

所以回答你的问题......你的代码出现以下错误:

  1. 取决于您的脚本 标签是在你的ul之前或之后 元素,你需要使用 $(document).ready function
  2. 您没有正确使用addClass回调...
  3. 你在addClass回调中有一个额外的括号“addClass(function()){”应该是“addClass(function(){”
  4. 没有.match方法就像你用过的那个......
  5. 这里有语法错误: '.attr(的 “href”)。';之后没有时间 '.attr'

    希望能回答你的问题。

答案 1 :(得分:4)

我认为这就是你要做的事情,有了评论,所以希望你能学到一些关于Javascript / jQuery的东西:

// when DOM is ready
$(function(){    

    // cache current URL
    var current_page = document.location.href;

    // use .each method to check link hrefs against current location
    $("ul#sol_menu li a").each(function () {

        // if this link is for the current page, highlight it
        if (current_page.indexOf(this.href) >= 0) {
            $(this).addClass('highlight');
        };

    });

});