
本文档旨在解决如何使用 JavaScript 从数组数据动态生成 HTML 按钮,并根据其类别进行组织的问题。通过使用 forEach 循环遍历数据,并利用模板字符串动态创建按钮元素,最终将这些按钮添加到对应的类别容器中。同时,还提供了打开游戏链接的 openGame 函数,以便用户点击按钮后能够在新窗口中打开游戏。
动态生成 HTML 按钮
要动态生成 HTML 按钮,首先需要一个包含按钮数据的数组。例如:
var buttonArr = [
{ "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/"}
];然后,可以使用 forEach 循环遍历该数组,并为每个数组项创建一个按钮元素。关键在于使用模板字符串(template literals)来动态生成按钮的 onClick 属性和按钮文本。
buttonArr.forEach(function (arrayItem) {
console.log(arrayItem.name);
console.log(arrayItem.url);
document.getElementById('buttonDiv').innerHTML += ``;
},);注意:
立即学习“Java免费学习笔记(深入)”;
- 确保 buttonDiv 元素在 HTML 中存在,并且其属性是 id="buttonDiv" 而不是 class="buttonDiv"。
- 使用模板字符串 (`...`) 可以方便地将变量嵌入到字符串中,例如 ${arrayItem.name} 和 ${arrayItem.url}。
- 在 onClick 属性中,需要使用双引号将 arrayItem.url 包裹起来,以确保 URL 作为字符串传递给 openGame 函数。
按类别组织按钮
为了按类别组织按钮,首先需要为每个类别创建一个 HTML 容器。例如:
Category 1
Category 2
如果需要更灵活的类别管理,可以动态创建类别容器。首先,获取所有不同的类别:
const categories = [...new Set(buttonArr.map(item => item.category))];
然后,动态创建类别标题和容器:
const container = document.getElementById('container'); //假设有一个id为container的元素
categories.forEach(category => {
const h1 = document.createElement('h1');
h1.textContent = category;
container.appendChild(h1);
const div = document.createElement('div');
div.id = `buttonDiv-${category}`;
container.appendChild(div);
});接下来,修改 forEach 循环,将按钮添加到对应的类别容器中:
buttonArr.forEach(function (arrayItem) {
const categoryDivId = `buttonDiv-${arrayItem.category}`;
document.getElementById(categoryDivId).innerHTML += ``;
},);关键点:
- 为每个类别创建一个唯一的 ID,例如 buttonDiv-Action。
- 在 forEach 循环中,根据 arrayItem.category 确定要将按钮添加到哪个容器。
打开游戏链接
openGame 函数用于在新窗口中打开游戏链接。
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);
}注意事项:
- 该函数使用 window.open() 方法创建一个新窗口。
- 它会创建一个 iframe 元素,并将游戏的 URL 设置为 iframe 的 src 属性。
- 为了确保游戏在新窗口中占据整个空间,需要设置 iframe 和 body 的样式。
- 使用 win 变量来缓存新窗口对象,以便在后续点击时可以直接聚焦到该窗口,避免创建过多的新窗口。
完整示例
以下是一个完整的示例,展示了如何动态生成 HTML 按钮并按类别组织它们:
Dynamic Buttons
总结
通过以上步骤,可以有效地使用 JavaScript 动态生成 HTML 按钮,并根据其类别进行组织。 这种方法可以用于构建动态的游戏列表、应用商店或其他需要根据数据生成 UI 元素的场景。 记住要正确使用模板字符串、确保 HTML 元素存在,并合理地组织代码结构,以提高代码的可读性和可维护性。











