简体   繁体   English

初学者的Javascript帮助,在条件为true的情况下打开链接的语句

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

I found this example: https://www.kirupa.com/html5/examples/detecting_internet_connection.htm it will alert you if internet exists or not, what i would like to do is when condition is true, not to allert me that the connection exists, but to open a link. 我发现了这个例子: https : //www.kirupa.com/html5/examples/detecting_internet_connection.htm它会警告您是否存在互联网,我想做的是在条件为真时,而不是向我暗示连接存在,但要打开一个链接。

<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;
    }
}

What i would like to do is in the: 我想做的是:

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

put a link like www.google.com and in the: 在以下位置放置一个链接,如www.google.com:

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

Change the alert to something that will open the link www.google.com 将警报更改为可以打开链接www.google.com的内容

This is going to be used in a webapp. 这将在webapp中使用。

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

You can use 您可以使用

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

I recommend visiting w3schools to see the available options http://www.w3schools.com/jsref/met_win_open.asp 我建议访问w3schools以查看可用的选项http://www.w3schools.com/jsref/met_win_open.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM