You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何遍历字符串数组生成CSS类选择器并在jQuery中正常使用

问题核心原因
  • 选择器变量未正确解析:循环内写的$('#card-content > item').show()中,item直接写在字符串内部,jQuery会将其识别为<item>标签的元素选择器,不会读取你定义的item变量值,因此无法匹配到对应类名的元素。
  • 最早尝试的拼接写法存在语法错误:$('#card-content > ('.' + item)')引号嵌套混乱,字符串提前闭合导致语法失效,无法正常执行。
    另外注意你往filtered_authors_set添加元素时已经提前拼接了.前缀,所以循环里的item本身已经带类选择器的点符号,不需要额外再加。
修复代码

将循环内的选择器改为字符串拼接即可正常识别变量:

(selected_authors_array).forEach(function (item, index) {
    console.log(item);
    // 字符串拼接变量到选择器中
    $('#card-content > ' + item).show();
    $('#grid-content > ' + item).show();
    $('#list-content > ' + item).show();
});
优化建议

你可以不用循环遍历,直接把数组合并为多类选择器一次性操作,执行效率更高:

const selector = selected_authors_array.join(',');
$('#card-content > ' + selector).show();
$('#grid-content > ' + selector).show();
$('#list-content > ' + selector).show();

内容的提问来源于stack exchange,提问作者relima

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 17:15:03