2016-11-04 133 views
2

我有一些麻煩,試圖在下面的一段代碼來代替單引號(「...」)用雙引號(「...」):是否有可能用雙引號替換這些單引號?

<img id="image" src="images/bird.jpg" onmouseover="PlaySound('mySound'); this.src='images/bird_second_frame.jpg'" 
onmouseout="StopSound('mySound'); this.src='images/bird.jpg'"> 

每當我試圖更換帶雙打的單引號,代碼中斷,我似乎無法找到不同的解決方案。我被告知不要使用單引號 - 這是一個例外嗎?

任何幫助表示讚賞。

+2

JavaScript中的單引號和雙引號是可以互換的。 – Pointy

+0

http://stackoverflow.com/questions/16450250/javascript-replace-single-quote-with-double-quote – prasanth

+0

這大多是一種風格。如果您通常使用雙引號,那麼當您在表示字符串的字符串內部構建內容時,您可以使用雙引號或使用單引號。由於轉義是PITA,所以使用其他引用類型更容易和更安全。在這個例子中,使用HTML的雙引號屬性是很好的。然後使用單引號引用JS中的字符串值是完全可以接受的,事實上,我認爲您無論如何都無法逃避引號,因爲HTML並沒有很好地處理這些問題。 – Dymos

回答

4

您不能在由"字符分隔的HTML屬性值內使用文字"。它會過早地終止屬性值。

您可以包含一個爲&quot;,但這會使代碼顯着難以閱讀。

<img id="image" src="images/bird.jpg" onmouseover="PlaySound(&quot;mySound&quot;); this.src=&quot;images/bird_second_frame.jpg&quot;" onmouseout="StopSound(&quot;mySound&quot;); this.src=&quot;images/bird.jpg&quot;"> 

我已經被告知沒有在所有使用單引號 - 這是一個例外?

不,您剛剛收到不好的建議。

JavaScript和HTML不區分'",除非確定哪些字符可以在它們之間出現而不被轉義。

在您的示例中使用'更簡單易讀。


更好的方法是儘量避免內聯JavaScript。

<img id="image" 
    src="images/bird.jpg" 
    data-sound="mySound" 
    data-frame="images/bird_second_frame.jpg"> 

<script> 
    var element = document.getElementById("image"); 
    element.addEventListener("onmouseover", play); 
    element.addEventListener("onmouseover", stop); 

    function play() { 
     PlaySound(this.dataset.sound); 
     this.dataset.original = this.src; 
     this.src = this.dataset.frame; 
    } 

    function stop() { 
     StopSound(this.dataset.sound); 
     this.src = this.dataset.original; 
    } 
</script> 
3

您不能在由雙引號限定的字符串中使用雙引號,因爲它們會結束字符串。

在這種情況下,您對單引號的使用看起來很合適。

1

您可以在JavaScript中自由使用單引號;它們在語法上等價於雙引號字符(儘管任何單個字符串常量必須由相同類型的引號綁定)。這也適用於HTML,所以你可以通過使用屬性值分隔符的單引號得到你的JavaScript雙引號:

<button onclick='alert("Hello World")'>Click Me</button> 

但是,如果你真的想雙引號無處不在,你能逃脫他們作爲HTML實體:

<button onclick="alert(&quot;Hello World&quot;)">Click Me</button> 

這是非常醜陋的,但它的工作原理:HTML解析器特別尋找引號字符。

best要做的事情是停止在您的HTML中嵌入JavaScript事件處理程序設置,並純粹使用JavaScript。