【问题标题】:If Page URL Contains Queries Do Something如果页面 URL 包含查询做某事
【发布时间】:2015-09-28 17:51:58
【问题描述】:

我是 JQuery 和 Javascript 的初学者。只是尝试做一些非常简单的事情。测试 URL 是否包含类似 ?:

之后的任何查询
http://stackoverflow.com/questions/**?example=test**

然后继续对 HTML 实现一些 CSS 样式更改。到目前为止,这是我所拥有的:

var $pageURL = window.location.search;

if ($pageURL.val() != "?") {

$("p").css("background-color", "blue");

}

任何帮助将不胜感激,谢谢。

【问题讨论】:

标签: javascript jquery css url


【解决方案1】:

你可以使用indexOf:

var $pageURL = window.location.search;

if ($pageURL.indexOf('?example=') > -1) {
    $("p").css("background-color", "blue");
}

你也可以使用regex:

var url = window.location.href;
/\?.*?example=/i.test(url)

更新

如果您只想检查 URL 是否包含查询字符串:

if (window.location.href.indexOf('?') > -1) {
    // Do Something
}

【讨论】:

    【解决方案2】:

    你可以这样做:

    if (window.location.toString().indexOf("?") !== -1) {
       // your code here
    }
    

    或者其他更快的变体:

    if (window.location.search !== "") {
        // code here
    }
    

    【讨论】:

    • 是的,那个变种非常好。但我最终将开始测试 URL 字符串中的特定单词,因此在这种情况下,您的第一个单词会更好。
    【解决方案3】:
    if(window.location.href.indexOf('?') > -1)
    {
       $("p").css("background-color", "blue");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-26
      • 2014-11-19
      • 2023-04-08
      • 2011-08-11
      • 2015-08-15
      • 2023-03-31
      • 2014-07-05
      • 2011-07-27
      相关资源
      最近更新 更多