Try this
function myFunc(target_div,num_buttons) {
function getBtn(i) {
var btn = document.createElement("input");
btn.setAttribute("type","button");
btn.setAttribute("value","button_"+i);
btn.className = "mybuttons";
btn.setAttribute("id","button_"+i);
return btn;
}
function doButtonPress(k){
alert(k);
}
for(var i=0; i<num_buttons; i++) {
var btn = getBtn(i);
btn.onclick = function(){
doButtonPress(this.id.replace('button_', ''));
}
target_div.appendChild(btn);
}
}
If you are adding the id and class to the button for using it with doButtonPress() only then following might be an easier solution.
function myFunc(target_div,num_buttons) {
function doButtonPress(k){
alert(k);
}
function getBtn(i) {
var btn = document.createElement("input");
btn.setAttribute("type","button");
btn.setAttribute("value","button_"+i);
btn.specialProperty = i;
btn.onclick = function(){
doButtonPress(this.specialProperty);
}
return btn;
}
for(var i=0; i<num_buttons; i++) {
target_div.appendChild(getBtn(i));
}
}
Accompanying HTML
<div id="mydiv" ></div>
<script type="text/javascript">
myfunc(document.getElementById("mydiv"),10);
</script>