ndfweb.cn

js創建一個input數組並綁定click事件的方法


2021-03-19 14:33:19 (3237)



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

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

<script type="text/javascript"> 

// 通過 getElementsByTagName 獲得都有 input 控件 
var inputs =document.getElementsByTagName("input"); 
// 為第0個button綁定onclick事件,alert一下 
inputs[0].onclick = function(){ 
alert("我測試一下"); 


// 為每一個button綁定onclick事件,alert一下 
for(var i=0;i<inputs.length;i++){ 
inputs[i].onclick = function(){ 
alert("我測試一下"); 



window.onload = function(){ 
// 定義一個數組 arrs 
var arrs = new Array(); 
// 循環添加 
for(var i=0;i<2;i++){ 
// 循環添加兩個 input type="button" value="新增"+i 
var input = document.createElement("input"); 
input.type = "button"; 
input.value = "新增" + i; 
// 記得把創建的 input 放入 arrs 中 
arrs.push(input); 
// 然後把 input 放入 id="add" 的div中 
document.getElementById("add").appendChild(input); 


// 同樣用 [0].onclick 綁定事件,依然沒有問題 
arrs[0].onclick=function(){ 
alert("我又測試一下"); 


}
</script> 

本文版权:http://www.ndfweb.cn/news-831.html
  NDF俱乐部
  国际域名注册
  建站咨询
简体中文 NDF网站建设淘宝店 | ICO图标在线生成 | 外贸网站建设 | 联系我们
©2007-2024 NDF Corporation 鲁ICP备08005967号 Sitemap - RSSRSS订阅