仅当url不包含锚标志时才执行脚本

时间:2012-04-16 10:13:53

标签: jquery url hash comments show-hide

我有以下脚本在我的网站www.riscograma.ro上工作,隐藏评论部分,除非另有说明:

jQuery(function($)  {
$('#comments').hide();
$('#showcomments').click(function(e)    {
    if($('#comments').is(':hidden'))    {
        $('#comments').show();
}   }); });

问题是个别评论或回复表单的链接不能再指向它们应该的位置,因为目标是隐藏的。

我认为,如果url中没有锚号(#),那么只能执行脚本。我尝试添加以下行(和变体):

jQuery(function($)  {
if(window.location.hash.indexOf("#")==0)    {
    $('#comments').hide();  }
    $('#showcomments').click(function(e)    {
        if($('#comments').is(':hidden'))    {
            $('#comments').show();
}   }); });

但它不起作用(即注释div始终可见)。

我做错了什么?

1 个答案:

答案 0 :(得分:3)

如果找不到,则{p> indexOf将返回-10表示已在索引0找到它。