JS HTML 單引號與雙引號

來源:互聯網
上載者:User

標籤:--   nbsp   type   錯誤   val   onclick   http   pre   ref   

JS中,單引號和雙引號其實沒啥區別,看你自己習慣了。但若雙引號中再使用雙引號,則需要用反斜線來禁止解析雙引號:alert("abc\"def\"ghi");
但如下情況需要明白:在一個網頁中的按鈕,寫onclick事件的處理代碼,不小心寫成如下:
<input type="button" onclick="alert("1")" /> -------------------不正確IE提示出錯後,再漫不經心地改為:
<input type="button" onclick="alert(\"1\")" /> ----------------不正確
結果還是出錯。這時,我就想不通了,雖然我知道最直接的解決方案是寫成這樣:
<input type="button" onclick="alert(‘1‘)" />  -------------------正確但為什麼javascript中的逸出字元\沒有效果了呢?
這是因為,這段代碼還是歸於HTML的管轄範圍,所以逸出字元應該使用HTML的,而不是javascript的。<input value="雙引號" type="button" onclick="alert(&quot;雙引號&#34;);" /> -------------------正確
<input value="單引號" type="button" onclick="alert(&apos;單引號&#39;);" /> -------------------正確
小結
<input value="外雙引號內雙引號-錯誤" type="button" onclick="alert("OK");" />
<input value="外單引號內單引號-錯誤" type="button" onclick=‘alert(‘OK‘);‘ />
<input value="兩個雙引號-錯誤" type="button" onclick="alert(""OK"");" />
<input value="兩個單引號-錯誤" type="button" onclick="alert(‘‘OK‘‘);" />
<input value="反斜線\+雙引號-錯誤" type="button" onclick="alert(\"OK\");" />
<input value="反斜線\+單引號-錯誤" type="button" onclick="alert(\‘OK\‘);" />

<input value="外雙引號內單引號-OK" type="button" onclick="alert(‘OK‘);" />
<input value="外單引號內雙引號-OK" type="button" onclick=‘alert("OK");‘ />
<input value="外部不使用引號-OK" type="button" onclick=alert(‘OK‘); />
註:內部使用HTML的單引號或雙引號轉移字元時,都是可以的

來自為知筆記(Wiz)

JS HTML 單引號與雙引號

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.