开发者

problem with jquery addClass function

<script>    
$("ul#sol_menu li a").addClass(function()) {
var current_page = document.l开发者_StackOverflow中文版ocation.href;
if ($(this).attr.("href").match(current_page)) {
$(this).addClass('highlight');
};
});
</script>

What is wrong with this?


I believe this might be what you were going for...
And as SLaks pointed out, your syntax (in this case) is a bit atrocious...

<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>

So to answer your question... the following was wrong with your code:

  1. Depending whether or not your script tag was before or after your ul element, you need to use the $(document).ready function
  2. You weren't using the addClass callback properly...
  3. You had an extra bracket at the addClass callback "addClass(function()) {" should have been "addClass(function() {"
  4. There's no .match method like the one you've used...
  5. You had a syntax error here: '.attr.("href")'; no period after '.attr'

    Hope that answers your question.


I think this is what you're trying to do, with comments so hopefully you learn something about 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');
        };

    });

});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜