我有一些 JSON 数据,它们是数组中的一系列对象,通过 PHP json_encode()
和 javascript fetch()
API 获取和输出。该数据包括多对多数据透视表链接表上 MySQL 联接的结果。本质上,它是输出特定的图像板数据,您可以在多个板上(显然是多个板上)拥有相同的图像。这一切都按预期工作。
背景
此数据的示例是:
[
{board_id: 428, board_name: 'tree board', image_id: 269}
{board_id: 428, board_name: 'tree board', image_id: 292}
{board_id: 426, board_name: 'Urban and City', image_id: 269}
{board_id: 426, board_name: 'Urban and City', image_id: 292}
{board_id: 426, board_name: 'Urban and City', image_id: 410}
{board_id: 365, board_name: 'random stuff', image_id: 269}
{board_id: 365, board_name: 'random stuff', image_id: 292}
]
在 JavaScript fetch()
的 then()
方法中,我尝试根据此数据创建一些按钮元素并将它们附加到父包装器,其中每个 board_id
值仅创建一个元素。
输出的 HTML 应该的示例:
<div class="wrapper">
<button value="428">tree board</button>
<button value="426">Urban and City</button>
<button value="365">random stuff</button>
</div>
问题
我无法解决的是如何将元素附加到包装器 div 内(最好使用模板字符串),以便每个 board_id
值只有一个实例获得按钮元素?
在这样的伪代码中:
let newButton = `
<button value="${board_id}">${board_name}</button>
`
我很高兴我需要在循环内执行此操作 - 对象数组被分配给 then()
方法中的 json
变量:
let wrapper = document.querySelector('.wrapper'); // the wrapper div
json.forEach( i => {
let boardName = i.board_name;
let boardId = i.board_id;
// -- somehow only only create a button on one instance of each board_id value
// -- append the single instance of the button inside the wrapper div
})
我在想,当涉及到附加模板字符串时,我需要在循环内使用类似的东西?
wrapper.insertAdjacentHTML('afterbegin', newButton);
问题摘要
如何仅为每个 board_id
值的一个实例输出/创建一个按钮元素,然后将其附加到父包装器中?
非常感谢任何帮助或建议
最佳答案
为了确保捕获按钮,以便创建两个单独的数组:一个包含现有的面板 ID,另一个包含按钮 HTML。
使用a loop 。如果 ids 数组中没有板 ID,请添加它,然后将按钮 HTML 添加到按钮数组中。然后就join
按钮数组向上,并将完整的 HTML 字符串添加到包装元素中。
const data=[{board_id:428,board_name:"tree board",image_id:269},{board_id:428,board_name:"tree board",image_id:292},{board_id:426,board_name:"Urban and City",image_id:269},{board_id:426,board_name:"Urban and City",image_id:292},{board_id:426,board_name:"Urban and City",image_id:410},{board_id:365,board_name:"random stuff",image_id:269},{board_id:365,board_name:"random stuff",image_id:292}];
const wrapper = document.querySelector('.wrapper');
const ids = [];
const buttons = [];
for (const { board_id, board_name } of data) {
if (!ids.includes(board_id)) {
ids.push(board_id);
buttons.push(`<button value=${board_id}>${board_name}</button>`);
}
}
wrapper.innerHTML = buttons.join('');
<div class="wrapper">
</div>
其他文档
关于javascript - 当数组中有多个实例时,以编程方式仅在 Javascript 对象属性的一个实例上创建 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74355197/