[英]Add body class to list of pages based on URL
我想將正文 class 添加到具有特定 URL 的頁面列表中。 For example, if the URL is /page1.html, /page2.html, /page3.html, /page4.html etc. etc. I would like to add a class to the body tag.
我的代碼有效,但非常臃腫。 有沒有辦法更優雅地寫這個? 總而言之,我需要檢查 10 個不同的 URL。
(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 或香草 JavaScript。
你可以這樣做: -
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));
將 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 href = document.location.href;
for (var i=1; i<=4; ++i) {
if (href.indexOf("page" + i + ".html") > -1) {
$('body').addClass('testclass');
}
}
使用數組操作來格式化這些格式有更好的方法,但概念是相同的。
我認為最優雅的方法是使用Array.some()
(function($) {
const pages = ['page1.html', 'page2.html' /* add whatever here */];
if (pages.some(page => document.location.href.indexOf(page) > -1)) {
$('body').addClass('testclass');
}
}(jQuery));
另一種方式
const pages = ['page1.html', 'page2.html', 'page3.html', 'page4.html'];
$('body').addClass(pages.find(page => ($(location).attr('pathname').includes(page))) && 'testclass');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.