Javascript 根据URL将主体类添加到页面列表中

Javascript 根据URL将主体类添加到页面列表中,javascript,jquery,Javascript,Jquery,我想在具有特定URL的页面列表中添加一个body类。例如,如果URL是/page1.html、/page2.html、/page3.html、/page4.html等,我想在body标记中添加一个类 我的代码可以工作,但它非常臃肿。有没有办法写得更优雅一些?总之,我需要检查10个不同的网址 (function($) { if ( document.location.href.indexOf('page1.html') > -1 || document.locati

我想在具有特定URL的页面列表中添加一个body类。例如,如果URL是/page1.html、/page2.html、/page3.html、/page4.html等,我想在body标记中添加一个类

我的代码可以工作,但它非常臃肿。有没有办法写得更优雅一些?总之,我需要检查10个不同的网址

(function($) {
    if ( document.location.href.indexOf('page1.html') > -1 ||
         document.location.href.indexOf('page2.html') > -1 || 
         document.location.href.indexOf('page3.html') > -1 ||
         document.location.href.indexOf('page4.html') > -1 ) {
             $('body').addClass('testclass');
    }
}(jQuery));

它可以是jQuery或vanilla JavaScript。

将URL添加到数组并在数组中循环:

var urls = ["page1.html", "page2.html", "page3.html", "page4.html"];
var href = document.location.href;
for (var i=0; i<urls.length; ++i) {
    if (href.indexOf(urls[i]) > -1)  {
      $('body').addClass('testclass');
    }
}
var url=[“page1.html”、“page2.html”、“page3.html”、“page4.html”];
var href=document.location.href;
对于(变量i=0;i-1){
$('body').addClass('testclass');
}
}
如果页面都是相同的格式,只需一个数字,您就可以动态构建它们,但您对添加/删除页面的控制较少,例如:

var href = document.location.href;
for (var i=1; i<=4; ++i) {
    if (href.indexOf("page" + i + ".html") > -1)  {
      $('body').addClass('testclass');
    }
}
var href=document.location.href;
对于(变量i=1;i-1){
$('body').addClass('testclass');
}
}

使用数组操作格式化这些文件有一些更奇特的方法,但概念是一样的。

您可以这样做:-

const pages = ['page1.html', 'page2.html', 'page3.html', 'page4.html'];

(function($) {
    pages.forEach(item => {
        if(document.location.href.indexOf(item) >=0)  {
            $('body').addClass('testclass');
        }
    });
}(jQuery));

我认为最优雅的方法是使用
Array.some()

另一种方式

const pages = ['page1.html', 'page2.html', 'page3.html', 'page4.html'];

$('body').addClass(pages.find(page => ($(location).attr('pathname').includes(page))) && 'testclass');

很好,简洁,但我希望他们没有把它称为
some
,在英语中,
some>1
(即2或更多,而不是1,通常超过2),这在javascript中不是这样的;其他系统称之为
。任何来自Scala的
,我也很难记住这个函数名。。。
const pages = ['page1.html', 'page2.html', 'page3.html', 'page4.html'];

$('body').addClass(pages.find(page => ($(location).attr('pathname').includes(page))) && 'testclass');