繁体   English   中英

Javascript中的引用问题

[英]Quotes issue in Javascript

我想每隔5秒在div中刷新一个img元素,指示用户是连接到互联网还是未连接。 如果用户已连接,则会在线显示图像,但如果用户处于脱机状态,则会显示本地图像。

但是,我无法解决这个引用问题。 我甚至试过“&-quot;” 事情(没有破折号),它仍然无法正常工作。 这是代码:

<script type="text/javascript">
    window.setInterval("refreshDiv()", 5000);
    function refreshDiv(){
    document.getElementById("test").innerHTML = "<img id="this" src="http://stallionware.weebly.com/uploads/3/0/4/3/30431988/4901948_orig.png" onerror="this.src='nowifi.png'">";
}
</script>
<div id=wifi>
<img id="this" src="http://stallionware.weebly.com/uploads/3/0/4/3/30431988/4901948_orig.png" onerror="this.src='nowifi.png'">
</div>

我不想使用jQuery或Ajax或任何服务器端语言,因为这都在本地机器上。

你可以逃避这样的双引号:

document.getElementById("this").innerHTML = "<img id=\"this\" src=\"http://stallionware.weebly.com/uploads/3/0/4/3/30431988/4901948_orig.png\" onerror=\"this.src='nowifi.png'\">";

通过键入\\"你告诉JavaScript你要在你的字符串中插入一个双引号。另一个选择是使用单引号。(我已经将你的getElementById从'test'改为'this',因为您的HTML没有'测试'作为Id)

此外,您不应该像在refreshDivrefreshDiv使用字符串调用函数。 相反,你应该这样称呼它的名字:

window.setInterval(refreshDiv, 5000);

您应该使用单引号和双引号的层次结构。 在双引号下使用双引号使JS认为是字符串的组合。 但没有运营商就失败了。

<script type="text/javascript">
    window.setInterval("refreshDiv()", 5000);
    function refreshDiv(){
    document.getElementById("test").innerHTML = '<img id="this" src="http://stallionware.weebly.com/uploads/3/0/4/3/30431988/4901948_orig.png" onerror="this.src='nowifi.png'">';
}
</script>
<div id=wifi>
<img id="this" src="http://stallionware.weebly.com/uploads/3/0/4/3/30431988/4901948_orig.png" onerror="this.src='nowifi.png'">
</div>

除了那个,而不是每5秒检查一次,我建议去使用浏览器的在线和离线事件 - 然后保存你的代码,使其不具备setInterval类的东西。

在JavaScript中,您可以使用单引号或双引号。 对于您的情况,您应该将包含div的字符串放在单引号中,并使用双引号在该字符串中包含HTML属性。 但是,无论如何,您的代码中似乎还有其他一些错误。 试试这个:

<img id="image" src="http://stallionware.weebly.com/uploads/3/0/4/3/30431988/4901948_orig.png" onerror="error">

在您的Javascript中有以下内容:

var theImage = document.getElementById('image');
function error() {
  theImage.src='nowifi.png';
}

function refreshDiv(){
  theImage.innerHTML = '<img id="image" src="http://stallionware.weebly.com/uploads/3/0/4/3/30431988/4901948_orig.png"     
  onerror="error">';
}
setInterval(refreshDiv, 5000);

暂无
暂无

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

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