【问题标题】:Using .indexOf on more than one url string在多个 url 字符串上使用 .indexOf
【发布时间】:2017-06-26 06:29:25
【问题描述】:

我有一个函数在页面的 URL 以 /about.html 结尾时运行

window.onload = function() {
    if (window.location.href.indexOf('/about.html') > -1) {
        $("#logo-black").typed({
            strings: ["Nothing^450&Co^250.^500", "^800__^400&Co^600."],
            typeSpeed: 70,
            backSpeed: 100,
            callback: function() {
                $(".typed-cursor").css("display", "none"),
                setTimeout(function(){
                    $('.main-load').toggleClass('main-load-active'),
                    $('.nav-text').toggleClass('nav-text-active');
                },400),
                $('.nav-reveal').toggleClass('nav-reveal-active');
            }
        });
    }
}

但我想将此功能应用到其他页面(contact.html 等)。

如何让 .indexOf 处理多个字符串?

感谢任何帮助/建议/建议/建设性批评! 我知道这是微不足道的,但我不确定哪种解决方案在这里最有效。

【问题讨论】:

  • 试试/(about-html|contact.html)/.test(window.location.href)
  • ['/about.html', '/contact.html', ... ].some(x => location.href.includes(x))
  • 字符串没有包含方法 @haim770 - 你的意思是 includes - 在 Internet Exploder 或 Oprah 中不起作用
  • @JaromandaX,你是对的。是控制台窗口误导了我,因为显然 StackOverflow 定义了这样的 contains 方法。

标签: javascript jquery href indexof


【解决方案1】:

您可以使用.test()

console.log(window.location.href)
if (/(about.html|contact.html|js)/.test(window.location.href)) {
  console.log("Contains either: about.html OR contact.html OR js")
} else {
  console.log("Can't find either: about.html OR contact.html OR js")
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

  • about-html 是从哪里来的?你是说about.html :p
  • @JaromandaX 非常真实,诚实的类型错误 :) 感谢您的提醒。
  • 感谢 Carsten,我会实施并报告 ?
猜你喜欢
  • 2023-04-02
  • 1970-01-01
  • 2021-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-22
  • 2016-02-03
  • 1970-01-01
相关资源
最近更新 更多