【问题标题】:Javascript - If url contains X, ignore script, else, run scriptJavascript - 如果 url 包含 X,忽略脚本,否则,运行脚本
【发布时间】:2012-06-05 22:01:05
【问题描述】:

我对 Javascript 比较陌生,我似乎无法让脚本在某些页面上运行/不运行。

我的主页上有这个脚本来隐藏和取消隐藏内容:

$(document).ready(function() {
$(".hidden").hide();
$(".show").html("[+]");
$(".show").click(function() {
    if (this.className.indexOf('clicked') != -1 ) {
        $(this).prev().slideUp(0);
        $(this).removeClass('clicked')
        $(this).html("[+]");
        }
        else {
        $(this).addClass('clicked')
        $(this).prev().slideDown(0);
        $(this).html("[–]");
        }
    });
});

我需要一些这样的编码:

如果 url 包含 "/post/" 则忽略脚本 否则运行脚本

这应该是一个简单的修复。我只是无法让它工作。有什么建议吗?

【问题讨论】:

    标签: javascript url


    【解决方案1】:

    您要查找的if 是:

    if (window.location.indexOf('/post/') == -1){
        // don't run, the '/post/' string wasn't found
    }
    else {
        // run
    }
    

    indexOf() 如果未找到字符串,则返回-1,否则返回字符串中找到字符串第一个字符的索引。

    上面重写了 Jason 提供的附加常识(在 cmets 中,如下):

    if (window.location.indexOf('/post/') > -1){
        // run, the '/post/' string was found
    }
    

    【讨论】:

    • 我会将其写为if (window.location.indexOf('/post/') >= 0){ // code to run here } 以避免(令人困惑的)空 if 块。
    【解决方案2】:

    根据this answer

    window.location 是一个对象,而不是一个字符串,所以它没有 indexOf 函数。

    ...所以window.location.indexOf() 将永远无法工作。

    但是,按照相同答案的指导,您可以将 URL 转换为带有 window.location.href 的字符串,然后执行搜索。或者您可以访问部分 URL,如下所示:

    if (window.location.pathname === '/about/faculty/'){ ... } 精确匹配

    window.location.pathname.split( '/' ) 获取部分 url,如 this answer 中所述。

    【讨论】:

      猜你喜欢
      • 2016-02-15
      • 2015-09-18
      • 1970-01-01
      • 2020-03-14
      • 1970-01-01
      • 2023-01-08
      • 1970-01-01
      • 1970-01-01
      • 2014-10-22
      相关资源
      最近更新 更多