Js creates an input array and binds a method to the click event

  • 2020-03-30 03:18:26
  • OfStack

 
</pre><pre name="code" class="javascript"><html> 
<body> 
<input type="button" name="input[]" value=" button 1" /><br /> 
<input type="button" name="input[]" value=" button 2" /><br /> 
<input type="button" name="input[]" value=" button 3" /><br /> 

<div id="add"></div> 
</body> 
</html> 

<script type="text/javascript"> 

//The input control is available through getElementsByTagName
var inputs =document.getElementsByTagName("input"); 
//Bind the onclick event for the 0th button, with an alert
inputs[0].onclick = function(){ 
alert(" Let me test that out "); 
} 

//Bind the onclick event for each button with an alert
for(var i=0;i<inputs.length;i++){ 
inputs[i].onclick = function(){ 
alert(" Let me test that out "); 
} 
} 

window.onload = function(){ 
//Define an array arrs
var arrs = new Array(); 
//Cycle to add
for(var i=0;i<2;i++){ 
//Loop to add two input types ="button" value=" add "+ I
var input = document.createElement("input"); 
input.type = "button"; 
input.value = " new " + i; 
//Remember to put the created input into the arrs
arrs.push(input); 
//Then put the input into the div with id="add"
document.getElementById("add").appendChild(input); 
} 

//Bind the event with [0].onclick again, no problem
arrs[0].onclick=function(){ 
alert(" Let me test that again "); 
} 

}
</script> 

Related articles: