使用 JavaScript 动态生成按钮并按类别组织

霞舞
发布: 2025-09-06 17:14:53
原创
802人浏览过

使用 javascript 动态生成按钮并按类别组织

本文档旨在指导开发者如何使用 JavaScript 动态地根据数据生成 HTML 按钮,并按照预定义的类别对这些按钮进行组织。我们将通过一个实际案例,演示如何利用数组数据,结合 DOM 操作,高效地创建按钮元素,并将其放置到对应的类别容器中,最终实现一个可交互的游戏列表页面。

动态生成按钮

首先,我们需要一个包含按钮数据的数组。 数组中的每个元素都应包含按钮的类别、名称和 URL。 例如:

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://example.com/2048" }
];
登录后复制

接下来,使用 forEach 循环遍历数组,并为每个元素创建一个按钮。使用模板字符串可以方便地将变量插入到 HTML 字符串中。

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免费学习笔记(深入)”;

AppMall应用商店
AppMall应用商店

AI应用商店,提供即时交付、按需付费的人工智能应用服务

AppMall应用商店 56
查看详情 AppMall应用商店
  • 确保 HTML 中存在一个 id 为 buttonDiv 的元素,用于存放生成的按钮。
  • 使用模板字符串(反引号 `)来创建包含变量的 HTML 字符串。
  • 使用 ${variable} 的语法将变量的值插入到字符串中。
  • openGame 函数用于处理按钮点击事件,打开指定 URL 的游戏。

按类别组织按钮

为了按类别组织按钮,我们需要为每个类别创建一个容器。可以在 HTML 中预先定义这些容器,或者使用 JavaScript 动态创建。 这里展示预先定义的方式:

<h1>Category 1</h1>
<div id="category1"></div>

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

然后,在循环遍历数组时,根据按钮的类别,将按钮添加到相应的容器中。

buttonArr.forEach(function (arrayItem) {
    const categoryId = arrayItem.category.toLowerCase().replace(/\s+/g, ''); // 将类别转换为 ID 格式
    const categoryDivId = `category${categoryId}`;
    let categoryDiv = document.getElementById(categoryDivId);

    // 如果类别容器不存在,则创建它
    if (!categoryDiv) {
        categoryDiv = document.createElement('div');
        categoryDiv.id = categoryDivId;
        document.body.appendChild(categoryDiv); // 或者添加到其他合适的父元素
        const categoryHeader = document.createElement('h1');
        categoryHeader.textContent = arrayItem.category;
        document.body.insertBefore(categoryHeader, categoryDiv); // 在div之前插入标题
    }

    categoryDiv.innerHTML += `<button onClick='openGame("${arrayItem.url}")'>${arrayItem.name}</button>`;
});
登录后复制

代码解释:

  1. 生成类别 ID: 将类别名称转换为小写,并移除空格,以生成一个有效的 HTML ID。
  2. 获取类别容器: 尝试获取与类别 ID 匹配的 HTML 元素。
  3. 创建类别容器(如果不存在): 如果不存在,则创建一个新的 div 元素,并将其添加到文档中。
  4. 添加按钮到容器: 将按钮添加到对应的类别容器中。

完整代码示例

<!DOCTYPE html>
<html>
<head>
<title>Dynamic Buttons</title>
</head>
<body>

  <div id="buttonDiv"></div>

  <script type="text/javascript">
    //start game code
    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://example.com/2048" }
    ];

    buttonArr.forEach(function (arrayItem) {
        const categoryId = arrayItem.category.toLowerCase().replace(/\s+/g, ''); // 将类别转换为 ID 格式
        const categoryDivId = `category${categoryId}`;
        let categoryDiv = document.getElementById(categoryDivId);

        // 如果类别容器不存在,则创建它
        if (!categoryDiv) {
            categoryDiv = document.createElement('div');
            categoryDiv.id = categoryDivId;
            document.body.appendChild(categoryDiv); // 或者添加到其他合适的父元素
            const categoryHeader = document.createElement('h1');
            categoryHeader.textContent = arrayItem.category;
            document.body.insertBefore(categoryHeader, categoryDiv); // 在div之前插入标题
        }

        categoryDiv.innerHTML += `<button onClick='openGame("${arrayItem.url}")'>${arrayItem.name}</button>`;
    });

    //end game code
    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>
登录后复制

注意事项

  • ID 的唯一性: 确保每个类别容器的 ID 在文档中是唯一的。
  • 安全性: 在动态生成 HTML 时,要小心处理用户输入,以防止跨站脚本攻击(XSS)。
  • 性能: 如果需要生成大量的按钮,考虑使用文档片段(DocumentFragment)来提高性能。
  • CSS 样式: 可以使用 CSS 来美化按钮和类别容器的样式。

总结

通过本文档,你学习了如何使用 JavaScript 动态地生成 HTML 按钮,并按照类别组织它们。这种方法可以用于创建动态的游戏列表、应用列表或其他需要根据数据生成 UI 元素的场景。 记住,清晰的代码结构、适当的错误处理和良好的性能优化是构建高质量 Web 应用的关键。

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

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源: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号