Javascript - 如果url包含X,则忽略脚本,否则运行脚本

时间:2012-06-05 22:01:05

标签: javascript url ignore

我对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("[–]");
        }
    });
});

我需要这样的编码:

如果网址包含" / post /"然后忽略脚本 否则运行脚本

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

2 个答案:

答案 0 :(得分:2)

您正在寻找的if是:

if (window.location.indexOf('/post/') == -1){
    // don't run, the '/post/' string wasn't found
}
else {
    // run
}
如果找不到字符串,则

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

以上改写了Jason提供的常识(在下面的评论中):

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

答案 1 :(得分:1)

根据this answer

  

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

...所以window.location.indexOf()永远不会奏效。

但是,在相同答案的指导下,您可以将网址转换为包含window.location.href的字符串,然后执行搜索。或者您可以访问URL的部分内容,如下所示:

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

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

相关问题