簡體   English   中英

如何基於當前URL在JavaScript中添加語句?

[英]How do I add a statement in javascript based on the current url?

基本上,我想檢查用戶使用的是哪個url並將其與默認值進行比較,然后運行一條語句

假設我的網址是https://stackoverflow.com/questions/ask ,我正在嘗試執行此操作,但它不起作用:

<script type="text/javascript">
      if(document.location.href('/questions/ask') > 0)
  {
    [do this];
  }

謝謝你的幫助(我知道的菜鳥問題)

試試看,您缺少indexOf方法。

if(document.location.href.indexOf('/questions/ask') > -1)

但是我相信您應該離開該窗口對象,我認為文檔已過時(但仍然可以使用)。

if(window.location.href.indexOf('/questions/ask') > -1)

您還希望檢查索引是否大於負1,因為從技術上講零是正確的位置。

嘗試這個:

var loc = new String(window.location);
if(loc.match('/questions/ask')) {
    // do something here
}

window.location.href為您提供整個網址。 您還可以訪問位置的其他屬性,例如protocolpathnamehashhost

if(window.location.pathname == '/questions/ask')

暫無
暫無

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

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