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

如何使用JS为用户新增的数组咖啡菜单项单独设置差异化样式

解决方案

你只需要给用户新增的咖啡对象加一个自定义标记字段,渲染的时候判断这个字段输出不同样式即可,不需要拆分原数组,改动非常小:

第一步:修改新增咖啡的逻辑,添加标记字段

你现在新增的newCoffee没有id也没有区分标记,我们补充这两个内容:

buildText.addEventListener('click', function (e) {
    e.preventDefault()
    var coffeeInput = search2.value
    var pickRoast2 = searchRoast2.value
    var newCoffee = {
        // 新增id,避免渲染时id字段为空
        id: coffees.length + 1,
        name:coffeeInput,
        roast:pickRoast2,
        // 新增自定义标记,标识这是用户添加的咖啡
        isCustom: true
    }
    coffees.push(newCoffee)
    tbody.innerHTML = renderCoffees(coffees)
    console.log(coffees)
})

第二步:修改渲染函数,针对标记输出差异化内容

调整renderCoffee函数,判断如果是用户新增的咖啡,就加上自定义class和new标识:

function renderCoffee(coffee) {
    // 判断是否是自定义咖啡,加上对应的class
    var cardClass = coffee.isCustom ? 'col col-padding custom-coffee' : 'col col-padding'
    var html = '<div class="' + cardClass + '">';
    html += '<div class="noId">' + coffee.id + '</div>';
    html += '<p>' + coffee.name + '&nbsp;' + coffee.roast;
    // 是自定义咖啡就加new标识
    if(coffee.isCustom) {
        html += '&nbsp;<span class="new-tag">new</span>';
    }
    html += '</p>';
    html += '</div>';
    return html;
}

第三步:加上你需要的自定义样式

在你的CSS里加上对应样式即可,举个参考示例:

/* 自定义咖啡卡片的特殊样式 */
.custom-coffee {
    background: #fff8e6;
    border: 1px solid #ffc107;
    border-radius: 4px;
}
/* new标签的样式 */
.new-tag {
    display: inline-block;
    padding: 2px 6px;
    font-size: 12px;
    background: #ff4d4f;
    color: #fff;
    border-radius: 4px;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 00:30:01