javascript - Regarding the problem of using js to determine the existence of a certain field in the url address
滿天的星座
滿天的星座 2017-05-19 10:31:26
0
2
410

I am now making a menu and use js to determine the address and add styles to the menu. If a certain address exists, I will add styles to the li of the menu. My current problem is that it feels very verbose to write out. I need to judge one by one. My current problem is that I want to write all these fields into one. Is it okay for you to judge without having to judge individually?
Search in a pile by judging whether a certain field exists in the url, and add the class if found. Thank you, God

 var hrefof = window.location.href;
    if (hrefof.indexOf('diannaodonghua') > 0) {
        $(".menu > li ").eq(2).addClass('cur');
    } else if (hrefof.indexOf('shejifb') > 0) {
        $(".menu > li ").eq(2).addClass('cur');
    } else if (hrefof.indexOf('gonggongguanxi') > 0) {
        $(".menu > li ").eq(2).addClass('cur');
    } else if (hrefof.indexOf('qiyecehua') > 0) {
        $(".menu > li ").eq(2).addClass('cur');
    } else if (hrefof.indexOf('jingjimaoyi') > 0) {
        $(".menu > li ").eq(2).addClass('cur');
    } else if (hrefof.indexOf('building') > 0) {
        $(".menu > li ").eq(1).addClass('cur');
    } else if (hrefof.indexOf('culture') > 0) {
        $(".menu > li ").eq(1).addClass('cur');
    } else if (hrefof.indexOf('news') > 0) {
        $(".menu > li ").eq(1).addClass('cur');
    } else if (hrefof.indexOf('recruit') > 0) {
        $(".menu > li ").eq(4).addClass('cur');
    }
滿天的星座
滿天的星座

reply all(2)
滿天的星座

Based on your thoughts

var hrefof = window.location.href;
var demo = {
    diannaodonghua:2,
    shejifb:2,
    gonggongguanxi:2,
    qiyecehua:2,
    jingjimaoyi:2,
    building:1,
    culture:1,
    news:1,
    recruit:4
}
for ( let o in demo ) {
    if ( hrefof.includes( o ) ) {
         $(".menu > li ").eq(demo[o]).addClass('cur');
    }
}
刘奇

Can be extracted using regular expressionhref中的字段:/w+(?==w+)/g

'https://www.baidu.com?time=1230&user=asdk&pwd=asjdf&'.match(/\w+(?=\=\w+)/g);

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!