首页 > 解决方案 > 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.

标签: javascripthtmlbutton

解决方案


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.


推荐阅读