搜索

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

碧海醫心
发布: 2025-09-06 16:57:11
原创
315人浏览过

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

本文旨在解决使用 JavaScript动态生成 HTML 按钮,并根据预定义的数据,将这些按钮按类别进行组织的问题。通过修改 HTML 元素属性以及使用模板字符串,可以有效地将按钮动态添加到页面,并实现点击按钮打开对应 URL 的功能。同时,展示了如何将按钮放置到对应的类别下,提高代码的可维护性和可读性。

动态生成按钮

前端开发中,经常需要根据数据动态生成 HTML 元素。以下示例展示了如何使用 JavaScript 从一个包含按钮信息的数组中动态生成按钮,并将其添加到指定的 div 元素中。

HTML 结构:

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

注意,这里将 div 的 class 属性修改为 id 属性,以便 JavaScript 代码可以通过 document.getElementById 方法准确地获取该元素。

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

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/"}
];

buttonArr.forEach(function (arrayItem) {
    console.log(arrayItem.name);
    console.log(arrayItem.url);
    document.getElementById('buttonDiv').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);
}
登录后复制

代码解释:

  1. buttonArr 是一个包含按钮信息的数组,每个对象包含 category(类别)、name(按钮名称)和 url(链接地址)。
  2. forEach 方法遍历 buttonArr 数组,对每个元素执行回调函数。
  3. document.getElementById('buttonDiv') 获取 id 为 buttonDiv 的 HTML 元素。
  4. .innerHTML += 将新的 HTML 字符串追加到该元素的内容中。
  5. 使用了模板字符串(Template literals) `...${expression}...` 来动态生成按钮的 HTML 代码。 ${arrayItem.name} 将按钮名称插入到按钮的文本中, ${arrayItem.url} 将按钮链接插入到 onClick 事件处理函数中。 注意,这里需要用双引号包裹 arrayItem.url,否则在HTML中会解析错误。
  6. openGame(url) 函数用于在新窗口或标签页中打开指定的 URL。如果窗口已经存在,则将其置于前台。

注意事项:

星火作家大神
星火作家大神

星火作家大神是一款面向作家的AI写作工具

星火作家大神31
查看详情 星火作家大神
  • 确保 HTML 元素存在并且 id 属性与 JavaScript 代码中使用的 getElementById 方法的参数匹配。
  • 使用模板字符串可以更方便地插入变量和表达式,避免字符串拼接错误。
  • openGame 函数可以根据实际需求进行修改,例如,使用 window.location.href 在当前窗口中打开链接。

按类别组织按钮

如果需要将按钮按类别进行组织,可以先创建一个对象,以类别作为键,按钮数组作为值。然后,根据这个对象动态生成 HTML 元素。

修改后的 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://bigfoot9999.github.io/html5-games/games/2048/"}
];

// 创建一个以类别为键,按钮数组为值的对象
const categorizedButtons = {};
buttonArr.forEach(item => {
    if (!categorizedButtons[item.category]) {
        categorizedButtons[item.category] = [];
    }
    categorizedButtons[item.category].push(item);
});

// 动态生成 HTML 元素
const buttonDiv = document.getElementById('buttonDiv');
for (const category in categorizedButtons) {
    if (categorizedButtons.hasOwnProperty(category)) {
        const categoryButtons = categorizedButtons[category];

        // 创建类别标题
        const categoryTitle = document.createElement('h2');
        categoryTitle.textContent = category;
        buttonDiv.appendChild(categoryTitle);

        // 创建按钮列表
        const buttonList = document.createElement('ul');
        categoryButtons.forEach(button => {
            const listItem = document.createElement('li');
            const buttonElement = document.createElement('button');
            buttonElement.textContent = button.name;
            buttonElement.onclick = function() { openGame(button.url); };
            listItem.appendChild(buttonElement);
            buttonList.appendChild(listItem);
        });
        buttonDiv.appendChild(buttonList);
    }
}

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);
}
登录后复制

代码解释:

  1. categorizedButtons 对象用于存储按类别组织的按钮。
  2. 遍历 buttonArr 数组,将按钮添加到对应的类别下。
  3. 遍历 categorizedButtons 对象,为每个类别动态生成标题和按钮列表。
  4. 使用 document.createElement 方法创建 HTML 元素,并设置其属性和内容。
  5. 使用 appendChild 方法将元素添加到 DOM 树中。

总结:

通过以上方法,可以有效地使用 JavaScript 动态生成 HTML 按钮,并按类别进行组织。这种方法可以提高代码的可维护性和可读性,并且可以方便地根据数据动态更新页面内容。在实际开发中,可以根据具体需求对代码进行修改和优化。 例如,可以使用 CSS 样式来美化按钮和列表的显示效果。

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

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

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

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

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