如何在jQuery的.removeClass方法中传入长选择器列表避免报错
jQuery多行选择器报错解决方案
你遇到的unterminated string literal报错有两个核心诱因:
- 普通双引号/单引号包裹的JavaScript字符串不支持直接跨行书写,你之前尝试的反斜杠转义换行如果没生效,大概率是转义符后不小心加了空格等隐形字符导致失效
- 你给出的调整后代码里,
#bottom-ncaab i, #bottom-ncaab small末尾漏了逗号,即使换行问题修复,选择器也会识别错误
解决方法
方法1:使用ES6模板字符串(最推荐,兼容性覆盖绝大多数现代浏览器)
用反引号`替代原来的双引号包裹选择器,模板字符串原生支持跨行,无需额外转义:
$("#bottom-nfl").click(function(){ $(`#bottom-mlb i, #bottom-mlb small, #bottom-nba i, #bottom-nba small, #bottom-ncaab i, #bottom-ncaab small, #bottom-profile i, #bottom-profile small`).removeClass("orange"); });
方法2:ES5兼容写法:字符串拼接
如果需要兼容IE等老旧浏览器,可将每行选择器单独用引号包裹后用加号拼接:
$("#bottom-nfl").click(function(){ $("#bottom-mlb i, #bottom-mlb small," + "#bottom-nba i, #bottom-nba small," + "#bottom-ncaab i, #bottom-ncaab small," + "#bottom-profile i, #bottom-profile small").removeClass("orange"); });
方法3:优化选择器逻辑(长期维护更友好)
给所有底部导航元素加统一的公共类(比如bottom-tab),后续不需要每次新增导航项都修改选择器:
$("#bottom-nfl").click(function(){ $(".bottom-tab i, .bottom-tab small").removeClass("orange"); });
内容的提问来源于stack exchange,提问作者Ryan Thomas
相关产品推荐
相关产品推荐

