簡體   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