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

如何从Header对象动态生成带指定类名与内容的按钮?

解决方案

直接修改header函数即可实现需求,代码如下:

function header(content) {
    const html = content.buttonContent.map((item, index) => {
        // 匹配对应索引的类名,兼容数组长度不一致的情况
        const className = content.classes[index] || '';
        return `<button class="${className}" onclick="document.location='${item}'">${item}</button>`;
    });

    return `
    <header>
        <img src="#" alt="foto" title="foto">
        <nav>
            ${html.join('')}
        </nav>
        <button class="burger-menu">menu</button>
    </header>`;
}

核心修改点

  • 动态添加类名:利用map的第二个参数index,从content.classes数组中取出对应位置的类名,通过|| ''处理数组长度不匹配的场景,避免出现无效类名
  • 替换固定按钮文本:把原代码中固定的123替换为${item},直接使用buttonContent里的内容作为按钮显示文本
  • 逻辑拆分:将类名赋值单独拎出来,提升代码可读性

内容的提问来源于stack exchange,提问作者the Alex Fire

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 07:57:06