2012-01-18 81 views
0

的一部分,我需要比較這個var foo = 'whatever'比較JavaScript變量與A HREF

<ul id="nav_main"><li><a href="index.php?pag=THIS">link</a></li></ul> 

,然後把class="current"匹配<li>內。

+0

我在問,因爲我不知道該怎麼做 – 2012-01-18 19:17:24

回答

5
var foo = 'whatever'; 
$("#nav_main li a").filter(function(index){ 
    return foo === this.href.match(/pag=(.*)/)[1]; 
}).parent().addClass("current"); 

會這樣嗎?

演示:http://jsfiddle.net/rREry/1

0
$('#nav_main li').each(function() { // loop through each <li> 
    if ($(this).find('a').attr('href') == foo) { // check against your var (not sure what exactly you wanted to check) 
     $(this).addClass('current');  // add the "current" class if it matches 
    } 
}); 
1
var foo = 'THIS'; 
$('a[href*="'+foo+'"]', '#nav_main').closest('li').addClass('current'); 

這個搜索有包含字符串的href屬性<a>標籤,並添加類的含<li>

0
if (foo == "<ul id="nav_main"><li><a href="index.php?pag=THIS">link</a></li></ul>"){ 
    foo.addClass("current") 
}