簡體   English   中英

為什么這個簡單的javascript不起作用?

[英]Why is this simple javascript not working?

js的新功能。 基本上,我試圖以此來檢測當前頁面的URL中是否存在字符串:

var url = window.location;
var param = /\?provider=/i;
if (url.search(param) != -1) {
    alert('it does exist');
} else
    alert('it does not exist');

當我手動定義url變量時,它會起作用

var url = 'http://google.com?provider='

但是,當我嘗試像上面的腳本中那樣動態地獲取它時,它不起作用,是否有任何方法可以使其起作用?

您希望在定位對象上具有href屬性,如下所示:

var url = window.location.href;
var param = /\?provider=/i;
if (url.search(param) != -1) {
    alert('it does exist');
} else
    alert('it does not exist');

location不是字符串,它是對象,並且沒有.href .search()方法, .href是具有此功能的字符串。

window.location是一個對象。 看一下定位對象的整個屬性集: https : //developer.mozilla.org/en/DOM/window.location

您所追求的是window.location.href;

暫無
暫無

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

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