【问题标题】:Hide element using JavaScript使用 JavaScript 隐藏元素
【发布时间】:2016-10-05 10:37:28
【问题描述】:

我想要的是使用 Javascript 隐藏某些元素。具体来说,我希望仅当 URL 包含文本“cli”时才显示此元素。我尝试使用下一个代码

    var regex = window.location.href;
if(regex.indexOf('cli')>-1){
$(window).load(function() {
    $("[routerlinkactive]")[1].remove();
});
}

routerlnkactive 部分分开工作。也就是说,如果没有编写 if 语句,则始终将其删除。但我希望它只适用于该 URL。我怎么能这样做?

似乎不适用于 xxx.html 或 xxx.html?cli=30

谢谢。

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    尝试使用 indexOf() 函数。所以像

     var regex = window.location.href;
     if(regex.indexOf('cli')>-1){ //if cli is there
            $("[routerlinkactive]")[1].hide(); //hide
      }
    

    如果没有找到返回-1,如果找到返回字符串位置号(从0开始)。

    另外,您应该使用.hide() 隐藏,而不是删除。

    更新:

    因为你说它仍然不工作,我刚刚检查过,这个工作:

    var regex = "xxxxxx.com?cli=50";
    if(regex.indexOf('cli')>-1){
       alert(true);
    }else{
       alert(false);
    }
    

    所以用 hide() 函数替换 alert() 并确保正确引用了 html(即使你说它工作正常?)。并且正则表达式的值应该是window.location.href。 尝试添加和删除“cli”,你会看到不同。

    【讨论】:

    • 似乎不起作用。它对 xxxx.html 和 xxxx.html?cli=30 的作用相同而且我正在使用 remove,因为 Jquery 的 hide() 函数似乎没有工作
    • 请更新您有问题的代码,然后看看。
    • 出于某种原因,即使不使用 Web 控制台,也无法隐藏。但是使用删除有效。谢谢。
    【解决方案2】:

    Remove() 不是正确的选择,它会从 DOM 中删除元素。

    使用hide()show()

    $(document).ready(function(){
        //Hide your element by default on page load
        $("[routerlinkactive]")[1].hide();
        if(window.location.href.indexOf("cli") > -1) {
            //If URL has "cli" then show that element.
            $("[routerlinkactive]")[1].show();
        }
    });
    

    Reference of indexOf()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-13
      • 1970-01-01
      • 1970-01-01
      • 2023-02-04
      • 2015-01-02
      • 2013-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多