我的jQuery代码有问题,它应该检测到互联网的连接.
function checkConnection() {
var connected = true;
var img = document.createElement('img');
img.src = "https://p5-zbjpil5uzqzqg-b5icu4xm7kglqch5-458861-i2-v6exp3-ds.metric.gstatic.com/v6exp3/6.gif";
img.onerror = function () {
connected = false;
};
return connected;
}
setInterval(function () {
var isConnected = checkConnection(); // checkConnection() comes from above code
if (isConnected) {
alert('internet');
} else {
alert('no internet');
}
}, 3000);
Run Code Online (Sandbox Code Playgroud)
无论我在线还是离线,都有相同的警报窗口INTERNET出现.你可以帮忙修改代码吗?小提琴可在下面找到,随时修改它.
非常感谢.
处理事件时,通常需要使用回调.
function checkConnection(callback) {
var img = document.createElement('img');
img.onerror = function () {
callback(false);
};
img.onload = function() {
callback(true);
};
img.src = "https://p5-zbjpil5uzqzqg-b5icu4xm7kglqch5-458861-i2-v6exp3-ds.metric.gstatic.com/v6exp3/6.gif";
}
setInterval(function () {
checkConnection(function(isConnected){
if (isConnected) {
console.log('internet');
} else {
console.log('no internet');
}
}); // checkConnection() comes from above code
}, 3000);
Run Code Online (Sandbox Code Playgroud)
否则,您将始终获得,true因为在错误回调有机会执行之前发生了返回.
此外,在处理onload和onerror事件时,您总是希望在设置src之前绑定事件,否则事件可能在绑定之前发生.