为什么不能在IF语句中访问ID值?

时间:2018-10-09 16:30:54

标签: javascript html

我想制作只允许IP地址与代码相同的设备的脚本,但是不能使用if语句来实现。当我在语句中写x.id时不起作用...想法?

<html>
<script type="text/javascript">
    window.onload = function () {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "https://api.ipify.org?format=jsonp&callback=DisplayIP";
        document.getElementsByTagName("head")[0].appendChild(script);
    };
    function DisplayIP(response) {
        var x = document.getElementById("ipaddress").innerHTML = response.ip;
    }
</script>
</head>
<p id=ipaddress></p>
<form name="login">
<input type="button" onclick="check()" value="check ip">
</form>

<script language="javascript">
function check()
{
 if(x.id == "22.333.444.555")
  {
    window.open('ipadressok.html')
  }
 else
 {
   alert("ip adress unknown")
  }
}
</script>
</html>

1 个答案:

答案 0 :(得分:1)

您可以添加getIPAddress函数。

触发检查功能时,可以将值分配给x。

这是必需的,因为x不是全局变量,如果在检查功能范围内声明之前引用,则不会定义x。

<html>
<script type="text/javascript">
window.onload = function () {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "https://api.ipify.org?format=jsonp&callback=DisplayIP";
    document.getElementsByTagName("head")[0].appendChild(script);
};

function DisplayIP(response) {
    document.getElementById("ipaddress").innerHTML = response.ip;
}

// Add this function here to retrieve the value of the ipAddress element.
function getIPAddress() {
    return document.getElementById("ipaddress").innerHTML;
}

function check() {
    // Declaring and assigning x in here
    var x = getIPAddress();
    
    if (x == "22.333.444.555") {
        window.open('ipadressok.html')
    } else {
        alert("ip adress unknown")
    }
}
</script>
</head>
<body>
<p id=ipaddress></p>
<form name="login">
    <input type="button" onclick="check()" value="check ip">
</form>
</body> 
</html>