JavaScript 中單引號 ' 與雙引號 " 功能完全相同,但在字串嵌套、HTML 屬性、選擇器字串等場景下,正確交替使用可避免語法錯誤。本文說明規範、常見錯誤與最佳實踐。
[attr="value"] 或 :contains('text'),需注意引號層級。quotes: ["error", "single"] 強制。// 選擇器含 :contains('文字')
$("ul li a").filter(":contains('佳能'),:contains('松下'),:contains('卡西歐')").css("color", "red");
// 動態生成 HTML
$("內容").appendTo("body");
// 事件綁定傳遞字串參數
$("button").click(function(){ showMsg('Hello "World"'); });
// 錯誤:雙引號嵌套雙引號,導致字串提早結束
$("ul li a").filter(":contains("佳能"),:contains("松下")").css("color", "red");
// 錯誤:HTML 屬性雙引號衝突
$("#box").html("內容");
const name = "張三";
const html = `
${name} 的名片
`;
$("#container").html(html);
alert('它說: "Hello"'); // 外單內雙
alert("它說: 'Hello'"); // 外雙內單
alert('它說: \'Hello\''); // 外單內單需轉義
alert("它說: \"Hello\""); // 外雙內雙需轉義
const jsonStr = '{"name": "張三", "age": 25}'; // 標準 JSON 必須雙引號鍵值
const obj = JSON.parse(jsonStr);
// .eslintrc.js
module.exports = {
rules: {
"quotes": ["error", "single", { "avoidEscape": true }],
// avoidEscape: true 允許在單引號字串中使用雙引號而不轉義
}
};
`...${var}...` 處理複雜嵌套。