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

如何用三元运算符为符合条件的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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 18:40:16