永发信息网

javascript 创建按钮,赋值问题

答案:2  悬赏:50  手机版
解决时间 2021-03-18 17:42
  • 提问者网友:温旧梦泪无声
  • 2021-03-17 22:09
&lt;body&gt;<br>&lt;div id=&quot;hehe&quot;&gt;<br>&lt;/div&gt;<br>&lt;script&gt;<br><br>function liebiao(i){alert(i)}<br><br>for(i=0;i&lt;10;i++){<br>var bb =document.getElementById(&quot;hehe&quot;);<br>var button = document.createElement('button');<br>button.innerHTML=&quot;aaa&quot;+i<br><br>button.onclick=function(){liebiao(i);}<br>hehe.appendChild(button);<br><br>}<br>&lt;/script&gt;<br>&lt;/body&gt;<br><br>请问各位大神如何才能正确传值,使按下按钮时分别显示0,1,2.......9<br>或者构造一个数组函数来实现?
最佳答案
  • 五星知识达人网友:woshuo
  • 2021-03-17 22:18
这是一个典型的闭包问题,外层添加如下代码即可。
(function(i){
button.onclick=function(){
liebiao(i);
}
})(i);
全部回答
  • 1楼网友:逃夭
  • 2021-03-17 22:43
function liebiao(i){alert(i)}<br><br>for(i=0;i&lt;10;i++){<br>var bb =document.getElementById(&quot;hehe&quot;);<br>var button = document.createElement('button');<br>button.innerHTML=&quot;aaa&quot;+i;<br>//将值保存在控件的属性中,click时再读取该属性<br>button.setAttribute(&quot;i&quot;,i);<br><br>button.onclick=function(){liebiao(this.getAttribute(&quot;i&quot;));}<br>hehe.appendChild(button);<br><br>}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯