【问题标题】:Better way to do this via pure javascript更好的方法是通过纯 JavaScript 做到这一点
【发布时间】:2023-04-02 16:22:01
【问题描述】:
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

  }

基本上,我对包含这些字符串的页面使用单独的 css。我可能超过 50 页。想知道是否有更干净的方法来写这个。将它们放入数组中?

【问题讨论】:

  • 如果您的 URL 包含 =3880512345 怎么办?
  • 你为什么不提取数字,尝试将其解析为int然后评估它的值?
  • 这是干什么用的?
  • 这是基于url参数应用css
  • 在后端添加类到正文可能更简单。然后有基于 body 类的 css 规则。 css 也不必等待 javascript 加载

标签: javascript string url


【解决方案1】:

JS some function,就是这样的东西:

let options = ["=38805","=38807","=38816"]; //...and the others
let link = window.location.href;

if( options.some( option => link.includes(option))){
    console.log('yay! =)');
}

您实际上是在检查您的选项数组,并询问有关数组中每个元素的问题:“您是否出现在我的 URL 中?”。

然后,仅当 options 数组中的一个或多个元素回答 true 到您的 includes 问题时,some 方法才会返回 true(在这种情况下,激活 if 语句)。


顺便说一句- JS 有另一种方法,涵盖了类似的思路。 the every metohd.

这个方法,你可以通过它的名字来理解,只有当数组中的所有元素都在回答true你的问题时才会返回true。

【讨论】:

  • 我喜欢这个解决方案,但请记住,IE 不支持 String.prototype.includes()。如果浏览器兼容性很重要,请使用 link.indexOf(option) > -1。
【解决方案2】:

用这样的东西把它清理一下怎么样:

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
}

【讨论】:

  • 我需要 d=38805 在 id
  • 那么 if (window.location.href.indexOf('=' + id.toString()) > -1) 变成 if (window.location.href.indexOf('d=' + id .toString()) > -1)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多