如何检查两个字符串是否与javascript中的if语句相同?

时间:2017-11-12 05:09:48

标签: javascript if-statement

最终目标:我正在尝试制作一个javascript文件,该文件将隐藏页面上的所有内容,除非该网址包含在黑名单中。

今日目标:使用if语句检查currentLocation变量是否等于某个网址。如果是这样的代码...如果不这样做代码...

到目前为止我有什么:

var currentLocation = window.location;
if (currentLocation == "https://www.google.com") {
   document.documentElement.style = "display:none";
}

5 个答案:

答案 0 :(得分:2)

你很亲密。这是更正后的代码。 window.location是一个对象,您必须在其中一个键上设置条件,例如:



if (window.location.origin === 'https://stacksnippets.net') {
  document.documentElement.style.display = 'none';
}

<div>
  Something to show
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用类并将此类添加到document.body

var currentLocation = window.location;
if (currentLocation.trim() === "https://www.google.com") {
   document.body.classList.add('hideAll');
}

CSS

.hideAll{
display:none
}

如果css不可用,请使用内联样式

document.body.style.display='none';

答案 2 :(得分:0)

由于您没有IDclass,因此您应使用body标记。您可以使用body获取getElementsByTagName代码并将其显示为none

var currentHostLocation = window.location.hostname;
if (currentHostLocation == "google.com") {
    document.getElementsByTagName("body").style.display = "none";
}

OR

var currentHostLocation = window.location.hostname;
if (currentHostLocation == "google.com") {
    document.getElementsByTagName("body").style = "display:none";
}

我相信,即使这应该有效:

document.body.style.display = "none";

答案 3 :(得分:0)

向window.location添加href方法。它以你拥有它的方式重新控制对象,但是使用href它会将href(地址)作为字符串返回

     window.location.href

答案 4 :(得分:0)

您应该使用以下代码获取当前hostname并隐藏所有内容:

var currentHostLocation = window.location.hostname;
alert(currentHostLocation);
if (currentHostLocation == "google.com") {
    document.body.style.display='none';
}