javascript - Adding Buttons dynamically HTML
问题描述
I need a list of buttons with functionality but the buttons won't be known until the website actually loads. This is the implementation I've been using:
var list = [1, 2, 3, 4, 5, 6, 7, 8];
function placeAnotherNumber(num)
{
document.getElementById("NumLabel").innerHTML += " " + num;
}
function putButtons()
{
var temp = "";
for(i = 0; i < list.length; i++)
{
temp += "<button onclick='placeAnotherNumber(" + list[i] + ");'>" + (i+1) + "</button>";
}
document.getElementById("ButtonLabel").innerHTML = temp;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="putButtons()";>Load</button>
<br/>
<label id='ButtonLabel'></label>
<br/>
<label id='NumLabel'></label>
</body>
</html>
After loading in the buttons, I hope the functionality would be to add whatever number I press to the label below the buttons. It does this but it also adds a 1 after. It's calling the method twice with the number and also with the first member in the list.
In Chrome this works as expected but my real code that I'm working on still doesn't.
This is my second week of HTML/JavaScript and I'm not sure what the issue is. Possibly just bad implementation. I'm not even sure what terms I should've been googling to solve this (dynamic button adding?).
Any ideas of how to fix this method or how I should really be doing this task?
Thanks in advance.
解决方案
The above code is working, it's highlighting the 1 button when you click on another button, but it is not appending any 1 after the last number added. If you change the label elements to divs then it won't look like you're clicking on the 1 as well. You shouldn't use labels for something like this. Those should be reserved for labels on input form elements in general.
推荐阅读
- api - 如何使用 long curl 命令正确解析 YAML
- python-3.x - FastAPI 使用 POST 请求将文件下载到客户端
- javascript - Docker 后端部署找不到路径'/app/package.json' - DigitalOcean
- flutter - 我可以在原生启动画面上放置超过 2 个图像吗?
- sql - 在 oracle 中分隔数值和字符值
- python - Python世纪日期过程
- bootstrap-4 - 切换按钮问题
- xaml - 将自定义按钮插入 BottomBar 外壳
- arrays - C中数组的大小小于预期
- dependency-injection - 是否可以使用 Unity 作为与 Restier 结合使用的 DI 框架