简体   繁体   中英

Comparing a javascript variable with a part of a href

I need to compare a var foo = 'whatever' with THIS:

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

And then, put class="current" inside the matched <li> .

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

Would that work?

Demo: http://jsfiddle.net/rREry/1

var foo = 'THIS';
$('a[href*="'+foo+'"]', '#nav_main').closest('li').addClass('current');

This searches for <a> tags that have an href attribute containing the string, and adds the class to their containing <li> .

$('#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
    }
});
if (foo == "<ul id="nav_main"><li><a href="index.php?pag=THIS">link</a></li></ul>"){
  foo.addClass("current")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM