在 jQuery 程式碼 $('#news tr:has(td):not(:contains("'+topic+'"))') 中,引號與加號的巢狀結構常讓初學者困惑。實際上這是 JavaScript 字串拼接的標準寫法。
'#news tr:has(td):not(:contains("' + topic + '"))'
// ^ 外層單引號開頭 ^ 雙引號包住 topic 變數值 ^ 外層單引號結尾
'#news tr:has(td):not(:contains("。:contains() 選擇器要求參數以雙引號括起,故在字串中寫成 "。topic 的值插入字串中間。:contains("... 後的單引號,接著再用加號連接結尾 '"))'。因為 topic 是 JavaScript 變數,其值(如 "Community")必須動態嵌入選擇器字串中。若直接寫死 :contains("Community") 就不具備動態性。拼接後產生的完整選擇器字串例如:
'#news tr:has(td):not(:contains("Community"))'
`#news tr:has(td):not(:contains("${topic}"))`
使用反引號 ` 與 ${...} 可大幅提升可讀性,避免引號巢狀錯誤。
:contains() 參數解析失敗。topic 中包含特殊字元(如引號)的情況,建議使用 .replace(/"/g, '\\"') 轉義。理解字串拼接機制,能靈活構建動態選擇器,也是 JavaScript 基礎功力的體現。