2014-02-12 57 views
20

我有一個帶有選擇選項的頁面,我使用JQuery刷新頁面並在單擊選項時向該URL添加字符串。現在我需要一種方法來檢查瀏覽器url,看它是否包含所述字符串。檢查url是否包含帶jQuery的字符串

尋找其他線程我認爲indexOf會工作,但試圖這樣做不起作用。如果URL包含?added-to-cart=555之類的內容,我還能檢查其他什麼?完整的URL通常如下所示:http://my-site.com,點擊其中一個選項後,它將在頁面重新載入後顯示爲:http://my-site.com/?added-to-cart=555。我只需要檢查URL是否包含?added-to-cart=555位。

以下是我有:

jQuery("#landing-select option").click(function(){ 

$('#product-form').submit(); 

    window.location.href += $(this).val() 

}); 

jQuery(document).ready(function($) { 
if(window.location.indexOf("?added-to-cart=555") >= 0) 
      { 
       alert("found it"); 
      } 
}); 
+6

難道你沒有注意到的錯誤'類型錯誤: window.location.indexOf不是控制檯中的函數嗎? [瞭解如何](http://www.creativebloq.com/javascript/javascript-debugging-beginners-3122820)[** debug ** JavaScript](https://developers.google.com/chrome-developer-tools /文檔/ JavaScript的調試)。閱讀[關於'window.location'的MDN文檔](https://developer.mozilla.org/en-US/docs/Web/API/Window.location)也很有幫助。 –

+0

更新到'window.location.href.indexOf(「string-to-match」)' – Abram

回答

62

Use Window.location.href to take the url in javascript. it's a property that will tell you the current URL location of the browser. Setting the property to something different will redirect the page.

if (window.location.href.indexOf("?added-to-cart=555") > -1) { 
    alert("found it"); 
} 
+1

感謝您的回答。 –

+0

它可能有助於解釋在這種情況下「> -1」做什麼......它看起來像添加這只是檢查此字符串是否存在於窗口href中。有沒有不同的方法來解決這個問題? –

+1

@john_h是的,在javascript indexOf方法中返回字符串的位置。如果搜索字符串可用,則返回大於或等於零(> = 0)。如果它不可用,它總是返回-1。 –

3

使用hrefindexof

<script type="text/javascript"> 
$(document).ready(function() { 
    if(window.location.href.indexOf("added-to-cart=555") > -1) { 
    alert("your url contains the added-to-cart=555"); 
    } 
}); 
</script> 
3
if(window.location.href.indexOf("?added-to-cart=555") >= 0) 

window.location.href,不window.location

9

window.location是一個對象,而不是字符串,所以你需要用window.location.href獲取實際的字符串URL

if (window.location.href.indexOf("?added-to-cart=555") >= 0) { 
    alert("found it"); 
} 
相關問題