1

我对 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/”,则忽略脚本,否则运行脚本

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

4

2 回答 2

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
}
于 2012-06-05T22:04:35.717 回答
1

根据这个答案

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

......所以window.location.indexOf()永远不会工作。

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

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

或者

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

于 2017-10-23T19:58:03.110 回答