萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 字串中單雙引號衝突的解決方案

常見錯誤場景

在 JS 字串中拼接 HTML 事件屬性時,常因引號層級過多導致語法錯誤:

// 錯誤:內層雙引號與外層衝突
html += '<a onclick="return removeOpenCss(' + e.point.lng + e.point.lat + ')">取消</a>';

// 錯誤:嘗試加雙引號卻導致字串中斷
html += '<a onclick="return removeOpenCss("' + e.point.lng + e.point.lat + '")">取消</a>';

正確轉義策略

**原則:在 JS 字串內部,用 HTML 實體編碼表示引號。**

  • 單引號 ' → &#39; 或 &apos;(HTML5)
  • 雙引號 " → &quot;

修正後代碼

html += '<a onclick="return removeOpenCss(&quot;' + e.point.lng + e.point.lat + '&quot;)">取消</a>';

瀏覽器解析 HTML 時,&quot; 會還原為 ",JS 執行時看到的是合法的 removeOpenCss("123.45")。

通用範本

<input type="button" value="Click Me"
       onclick="showMsg('&quot;FSDFDS&quot;')" />
<input type="text" id="txtName" value="'&quot;FSDFDS" />

<script>
function showMsg(s) { alert(s); } // 彈出: "FSDFDS"
</script>

最佳實踐建議

  1. **避免內聯事件**,改用 addEventListener / jQuery .on() 綁定,完全跳脫引號地獄。
  2. 若必須拼接 HTML,使用**模板字面量**(ES6 `...`)搭配 ${var},可直接包含雙引號:
const html = `取消`;
copyright © 萬盛學電腦網 all rights reserved