Javascript 循环绑定事件
方法一
<script language="javascript">
$(document).ready(function(){
var bts = $("input");
var l = bts.length;
for(var i=0;i<l;i++)
{
bts[i].onclick = new function(n)
{
return function(){ alert(n)};
}(i);
}
});
</script>
<input type="button" name="button1" id="button1" value="按钮" />
<input type="button" name="button2" id="button2" value="按钮" />
<input type="button" name="button3" id="button3" value="按钮" />
<input type="button" name="button4" id="button4" value="按钮" />
<input type="button" name="button5" id="button5" value="按钮" />
<input type="button" name="button6" id="button6" value="按钮" />
$(document).ready(function(){
var bts = $("input");
var l = bts.length;
for(var i=0;i<l;i++)
{
bts[i].onclick = new function(n)
{
return function(){ alert(n)};
}(i);
}
});
</script>
<input type="button" name="button1" id="button1" value="按钮" />
<input type="button" name="button2" id="button2" value="按钮" />
<input type="button" name="button3" id="button3" value="按钮" />
<input type="button" name="button4" id="button4" value="按钮" />
<input type="button" name="button5" id="button5" value="按钮" />
<input type="button" name="button6" id="button6" value="按钮" />
方法二
$(document).ready(function(){
var bts = $("input");
var l = bts.length;
for(var i=0;i<l;i++)
{
(function(){
var p = i;
bts[p].onclick = function(){alert(p);}
})();
}
});
<input type="button" name="button1" id="button1" value="按钮" />
<input type="button" name="button2" id="button2" value="按钮" />
<input type="button" name="button3" id="button3" value="按钮" />
<input type="button" name="button4" id="button4" value="按钮" />
<input type="button" name="button5" id="button5" value="按钮" />
<input type="button" name="button6" id="button6" value="按钮" />
var bts = $("input");
var l = bts.length;
for(var i=0;i<l;i++)
{
(function(){
var p = i;
bts[p].onclick = function(){alert(p);}
})();
}
});
<input type="button" name="button1" id="button1" value="按钮" />
<input type="button" name="button2" id="button2" value="按钮" />
<input type="button" name="button3" id="button3" value="按钮" />
<input type="button" name="button4" id="button4" value="按钮" />
<input type="button" name="button5" id="button5" value="按钮" />
<input type="button" name="button6" id="button6" value="按钮" />