<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:
- Depending whether or not your script tag was before or after your ul element, you need to use the $(document).ready function
- You weren't using the addClass callback properly...
- You had an extra bracket at the addClass callback "addClass(function()) {" should have been "addClass(function() {"
- There's no .match method like the one you've used...
- 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');
};
});
});
精彩评论