初学者的Javascript求助,什么语句开一个linkif条件为真

Beginner's Javascript Help, what statements to open a link if condition is true

我找到了这个例子:https://www.kirupa.com/html5/examples/detecting_internet_connection.htm 它会提醒你是否存在互联网,我想做的是当条件为真时,不是提醒我连接存在,而是打开一个 link.

<div id="mainContainer">    
<a href="javascript:void(0)">Check connection!</a>
</div>

var link = document.querySelector("#mainContainer a");
link.addEventListener("mousedown", checkConnection, false);

function checkConnection(e) {
    if (doesConnectionExist() == true) {
        alert("connection exists!");
    } else {
        alert("connection doesn't exist!");
    }
}

function doesConnectionExist() {
    var xhr = new XMLHttpRequest();
    var file = "http://www.kirupa.com/images/giant_cloud.png";
    var randomNum = Math.round(Math.random() * 10000);

    xhr.open('HEAD', file + "?rand=" + randomNum, false);

    try {
        xhr.send();

        if (xhr.status >= 200 && xhr.status < 304) {
            return true;
        } else {
            return false;
        }
    } catch (e) {
        return false;
    }
}

我想做的是:

<a href="javascript:void(0)">Check connection!</a>

像 www.google.com 一样放一个 link 并在:

if (doesConnectionExist() == true) {
    alert("connection exists!");

将警报更改为可以打开 link www.google.com

这将在网络应用程序中使用。

 if (doesConnectionExist() == true) {
        window.open("https://www.google.com",'_blank');
    }
if (doesConnectionExist() == true) {
    window.location = 'http://www.google.com';
}

您可以使用

window.open("www.google.com");

我建议访问 w3schools 以查看可用选项 http://www.w3schools.com/jsref/met_win_open.asp