使用 JavaScript 动态生成 HTML 元素并按类别组织

DDD
发布: 2025-09-06 17:47:24
原创
437人浏览过

使用 javascript 动态生成 html 元素并按类别组织

本文档旨在解决如何使用 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 += `<button onClick='openGame("${arrayItem.url}")'>${arrayItem.name}</button>`;
},);
登录后复制

注意:

立即学习Java免费学习笔记(深入)”;

  • 确保 buttonDiv 元素在 HTML 中存在,并且其属性是 id="buttonDiv" 而不是 class="buttonDiv"。
  • 使用模板字符串 (`...`) 可以方便地将变量嵌入到字符串中,例如 ${arrayItem.name} 和 ${arrayItem.url}。
  • 在 onClick 属性中,需要使用双引号将 arrayItem.url 包裹起来,以确保 URL 作为字符串传递给 openGame 函数。

按类别组织按钮

为了按类别组织按钮,首先需要为每个类别创建一个 HTML 容器。例如:

<h1>Category 1</h1>
<h1>Category 2</h1>
<div id="buttonDiv"></div>
登录后复制

如果需要更灵活的类别管理,可以动态创建类别容器。首先,获取所有不同的类别:

const categories = [...new Set(buttonArr.map(item => item.category))];
登录后复制

然后,动态创建类别标题和容器:

Blackink AI纹身生成
Blackink AI纹身生成

创建类似纹身的设计,生成独特纹身

Blackink AI纹身生成 17
查看详情 Blackink AI纹身生成
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 += `<button onClick='openGame("${arrayItem.url}")'>${arrayItem.name}</button>`;
},);
登录后复制

关键点:

  • 为每个类别创建一个唯一的 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 按钮并按类别组织它们:

<!DOCTYPE html>
<html>
<head>
    <title>Dynamic Buttons</title>
</head>
<body>
    <div id="container"></div>

    <script type="text/javascript">
        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/"},
            { "category":"Puzzle","name":"2048","url":"https://play2048.co/"}
        ];

        const categories = [...new Set(buttonArr.map(item => item.category))];

        const container = document.getElementById('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);
        });


        buttonArr.forEach(function (arrayItem) {
            const categoryDivId = `buttonDiv-${arrayItem.category}`;
            document.getElementById(categoryDivId).innerHTML += `<button onClick='openGame("${arrayItem.url}")'>${arrayItem.name}</button>`;
        },);

        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>
</body>
</html>
登录后复制

总结

通过以上步骤,可以有效地使用 JavaScript 动态生成 HTML 按钮,并根据其类别进行组织。 这种方法可以用于构建动态的游戏列表、应用商店或其他需要根据数据生成 UI 元素的场景。 记住要正确使用模板字符串、确保 HTML 元素存在,并合理地组织代码结构,以提高代码的可读性和可维护性。

以上就是使用 JavaScript 动态生成 HTML 元素并按类别组织的详细内容,更多请关注php中文网其它相关文章!

HTML速学教程(入门课程)
HTML速学教程(入门课程)

HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号