简体   繁体   中英

search url for matching string in Jquery

I'm trying to search url for a matching string with jquery and if it matches add these classes to an html element. I have this code:

$(function () {
 var adminNav = [ "book_values", "lsi_print_costs", "book_specs"];
 var url = window.location.href;
 if (url.search(adminNav) > 0) {
    $('li#nav-admin.dark-nav').addClass('active');
    $('#print-admin').addClass('in');
 }
});

Any help would be greatly apperciated

Use Javascript:

if(window.location.search.indexOf("book_values") >=0) {
    $('li#nav-admin.dark-nav').addClass('active');
    $('#print-admin').addClass('in');
}

Use .map() to search if the window.location.href contains any value in the array.

var adminNav = ["book_values", "lsi_print_costs", "book_specs"];
var found = false;
adminNav.map(function (val) {
    if (window.location.href.contains(val) && !found) {
        found = true;
        $('li#nav-admin.dark-nav').addClass('active');
        $('#print-admin').addClass('in');
    }
});

Try this.

$(function () {
 var adminNav = [ "book_values", "lsi_print_costs", "book_specs"];
 var isExist = false;
 var url = window.location.href;
for(var i=0; i<adminNav.length; i++ )
{
 if (url.search(adminNav[i]) > 0 && !isExist) {
   isExist = true;
 }
}

if(isExist)
{
 $('li#nav-admin.dark-nav').addClass('active');
 $('#print-admin').addClass('in');
}
});

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