如何用三元运算符为符合条件的poll__option元素添加-selected类
解决方案
直接在模板字符串的class属性中嵌入三元运算符即可实现需求,同时修正原代码里的拼写错误(percentege → percentage):
for (const item of data) { const template = document.createElement("template"); const fragment = template.content; template.innerHTML = ` <div class="poll__option ${selected === item.label ? '-selected' : ''}"> <div class="poll__option-fill"></div> <div class="poll__option-info"> <span class="poll__label">${item.label}</span> <span class="poll__percentage">${item.percentage}</span> </div> </div> `; // 记得将生成的片段添加到目标DOM容器中,示例:document.querySelector('.poll-container').appendChild(fragment); }
核心说明
- 三元运算符
selected === item.label ? '-selected' : ''会在selected与当前遍历项的label匹配时,为目标div追加-selected类;不匹配时则添加空字符串,不额外增加类名。 - 修正了原代码中
percentege的拼写错误,改为正确的percentage。
内容的提问来源于stack exchange,提问作者Shant Krikorian
相关产品推荐
相关产品推荐

