Javascript:如何检查 URL 是否包含单词

新手上路,请多包涵

我想检查浏览器中的 URL 是否包含“桌面”一词(我从桌面启动 html 文件)。它的 url 是:“file:///C:/Users/Joe/Desktop/TestAlert.html”

但是应该会出现警报,但这不起作用。

这是我的代码:

 <html>
<head>
<script type="text/javascript">
$(document).ready(function () {
    if(window.location.href.contains("Desktop") > -1) {
       alert("Alert: Desktop!");
    }
});
</script>
</head>
<body>
    <h1>Test001</h1>
</body>
</html>

我在 Firefox、Chrome 和 Internet Explorer 中对此进行了测试。如果有人可以帮助我,那就太好了!

原文由 Joe SharePoint 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 281
2 个回答

该方法是 String.prototype.indexOf()

 if(window.location.href.indexOf("Desktop") > -1) {
       alert("Alert: Desktop!");
}

并且您不需要为此准备好 DOM。

原文由 void 发布,翻译遵循 CC BY-SA 3.0 许可协议

<html>
<head>
<script type="text/javascript">
$(document).ready(function () {
    if(window.location.href.indexOf("Desktop") > -1) {
       alert("Alert: Desktop!");
    }
});
</script>
</head>
<body>
    <h1>Test001</h1>
</body>
</html>

请试试这个它会给你解决方案

原文由 Naitik Patel 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题