簡體   English   中英

Javascript:如何檢查 URL 是否包含單詞

[英]Javascript: How to check if URL contains a word

我想檢查瀏覽器中的 URL 是否包含“桌面”一詞(我從桌面啟動 html 文件)。 它的網址是:“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 中對此進行了測試。 如果有人可以幫助我,那就太好了!

方法是String.prototype.indexOf()

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

並且你不需要DOM就緒。

<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>

請嘗試這個它會給你sollution

請改用indexOf

console.log(window.location.href.indexOf("javascript"));

同樣的規則適用,任何> -1表示它已找到一些東西

你可以使用正則表達式

url = window.location.href;
if( url.match(/desktop/gi) ) {
   alert("Alert: Desktop!");
}

使用它你可以檢查兩個或多個單詞,如“/ desktop | home / gi”

如果你想使用jQuery,你需要鏈接到它的源代碼。 另外,使用indexOf而不是contains

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

提示:當您遇到Javascript問題時,請在瀏覽器中按f12打開開發工具,然后按f5刷新頁面。 然后檢查控制台選項卡上是否有錯誤消息,例如“Uncaught ReferenceError:$ is not defined”,以及代碼中用紅色下划線標出的任何部分的sources選項卡。

var url = window.location.href;
            console.log(url);
            console.log(~url.indexOf("#product-consulation"));
            if (~url.indexOf("#product-consulation")) {
                console.log('YES');
                // $('html, body').animate({
                //     scrollTop: $('#header').offset().top - 80
                // }, 1000);
            } else {
                console.log('NOPE');
            }

if(window.location.href.indexOf("你想要的詞放在這里") > -1) { alert("這個詞在那里!"); }

完全符合您的要求!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM