[英]Better way to do this via pure javascript
if(window.location.href.indexOf("=38805") > -1
|| window.location.href.indexOf("=38807") > -1
|| window.location.href.indexOf("=38816") > -1
|| window.location.href.indexOf("=38815") > -1
|| window.location.href.indexOf("=38814") > -1
|| window.location.href.indexOf("=38813") > -1
|| window.location.href.indexOf("=38811") > -1
){
do something
}
Basically, I am using a separate css for the pages that contain these strings. 基本上,我对包含这些字符串的页面使用单独的css。 I might over 50 pages. 我可能超过50页。 Wondering if there is a cleaner way to write this. 想知道是否有更清晰的方式来写这个。 Put them into an array? 把它们放入一个数组?
JS some
function , is exactly for stuff like that: JS的some
功能 ,就是这样的东西:
let options = ["=38805","=38807","=38816"]; //...and the others
let link = window.location.href;
if( options.some( option => link.includes(option))){
console.log('yay! =)');
}
You're actually going through your array of options, and asking a question about each of the elements in the array : "Are you present at my URL?". 您实际上正在浏览您的选项数组,并询问有关数组中每个元素的问题:“您是否出现在我的URL中?”。
Then, the some
method will return true (and in this case- active the if
statment ) only if one or more elements in the options
array is answering true
to your includes
question. 然后,只有当options
数组中的一个或多个元素对includes
问题回答为true
, some
方法才会返回true(在这种情况下,激活if
语句)。
And by the way- JS have another method that cover a similar set of mind. 顺便说一句,JS有另一种方法可以涵盖类似的思维方式。 the every
metohd . every
metohd 。
This method, as you can understand by its name, will return true only if all the elements in the array is answering true
to your question. 这种方法,你可以用它的名字理解,将返回true,只有当阵列中的所有元素的回答true
到你的问题。
How about something like this to clean it up a bit: 这样的事情如何清理一下:
const ids = [38805, 38807, 38811, 38813, 38814, 38815, 38816];
let windowHrefHasId = false;
for (let id of ids) {
if (window.location.href.indexOf('=' + id.toString()) > -1) {
windowHrefHasId = true;
break;
}
}
if (windowHrefHasId) {
// do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.