阵列项目不在< div>中构建HTML元素
我需要我的程序来在每个类别下构建按钮,现在我的代码正遇到构建按钮的问题。我也不知道如何组织各自类别下的按钮。
<h1>Category 1</h1>
<h1>Category 2</h1>
<div class="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/"}
]
buttonArr.forEach(function (arrayItem) {
console.log(arrayItem.name);
console.log(arrayItem.url);
document.getElementById('buttonDiv').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>
I need my programs to build buttons under each category and right now my code is having issues building the buttons. I also have no clue how to organize the buttons under their respective categories.
<h1>Category 1</h1>
<h1>Category 2</h1>
<div class="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/"}
]
buttonArr.forEach(function (arrayItem) {
console.log(arrayItem.name);
console.log(arrayItem.url);
document.getElementById('buttonDiv').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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将“类属性”分配给了Buttondiv,我将其更改为id属性为buttondiv。
在创建按钮时,我还使用了模板字符串作为模板字符串允许我们以以下格式编写表达式$ {variable/expression}
You assigned class attribute to the buttonDiv, I changed it to id attribute to the buttonDiv.
I also used template strings while creating buttons as template string allows us to write expressions in the following format ${variable/expression}