JS遍历数组无法在div内渲染按钮及按分类排布问题
问题根因
你的代码跑不通、按钮没法按分类排布是三个低级错误导致的:
- 你写的按钮容器
<div class="buttonDiv">只加了class,代码里却用document.getElementById('buttonDiv')去获取元素,根本拿不到DOM节点,按钮当然渲染不出来 - 拼接按钮HTML的时候直接把
arrayItem.url、arrayItem.name当静态字符串写在标签里,没有插入变量值,最后生成的按钮上文字就是固定的arrayItem.name,点击时还会因为全局找不到arrayItem变量直接报错 - 你把两个分类标题硬编码在最前面,所有按钮都往同一个容器里塞,根本没做分类和按钮的关联逻辑,自然没法把按钮放到对应分类下面
可直接运行的修复代码
<div id="root"></div> <script> // 游戏数据源,后续新增游戏/分类直接往这个数组加对象即可 const gameList = [ { "category":"Action","name":"Temple Run 2","url":"https://bigfoot9999.github.io/html5-games/games/templerun2/"}, { "category":"Action","name":"Slope Game","url":"https://bigfoot9999.github.io/Slope-Game/"} ] const root = document.getElementById('root') // 先按分类对游戏做分组 const groupByCategory = {} gameList.forEach(game => { if (!groupByCategory[game.category]) groupByCategory[game.category] = [] groupByCategory[game.category].push(game) }) // 逐个渲染分类标题+对应按钮 Object.entries(groupByCategory).forEach(([categoryName, games]) => { // 插入分类标题 const title = document.createElement('h1') title.textContent = categoryName root.appendChild(title) // 插入当前分类的按钮容器 const btnWrap = document.createElement('div') btnWrap.className = 'buttonDiv' // 生成当前分类下所有按钮 games.forEach(game => { const btn = document.createElement('button') btn.textContent = game.name btn.addEventListener('click', () => openGame(game.url)) btnWrap.appendChild(btn) }) root.appendChild(btnWrap) }) let win; function openGame(url) { if (win) { win.focus(); return; } win = window.open(); win.document.body.style.margin = '0'; win.document.body.style.height = '100vh'; const iframe = win.document.createElement('iframe'); iframe.style.border = 'none'; iframe.style.width = '100%'; iframe.style.height = '100%'; iframe.style.margin = '0'; iframe.src = url; win.document.body.appendChild(iframe); } </script>
改动说明
- 删掉了硬编码的分类标题,先对数据源按分类做分组,后续新增分类、游戏不需要调整页面结构,改数据源就行
- 不用innerHTML拼接字符串的方式生成元素,改用原生DOM方法创建节点、绑定事件,彻底避免字符串插值错误、作用域报错问题
- 每个分类的按钮容器直接紧跟在对应分类标题后面插入,自动完成归类排布
- 修正了DOM选择器不匹配的问题,所有内容统一挂载到id为
root的容器下,不会出现拿不到节点导致渲染失败的问题
内容的提问来源于stack exchange,提问作者Bigfoot9999
相关产品推荐
相关产品推荐

