<html>
<script language=javascript>
function test()
{
for(var i=1;i<100;i++)
{
var a = document.createElement("a");
var txt = document.createTextNode("test");
a.appendChild(txt);
a.setAttribute("onclick",new function ()
{
return function()
{myfunc(i);}
});
var xx = document.getElementById('xx');
xx.appendChild(a);
}
} function myfunc(str)
{
alert(str+ ": ");
}
</script>
<body>
<input type=button value=test onclick= "test() "> <br>
<table id="tb" width=200 border=1>
<tr> <td bgcolor=yellow> 1111111111 </td> </tr>
</table>
<table width="760" border="0">
<tbody>
<tr>
<td id="xx"> </td>
<td> </td>
</tr>
</tbody>
</table>
</body>
</html> 动态生成结点A并给每个结点追加一个方法,
我希望每个A结点的onclick方法的参数都是外部循环的值,也就是这里的i值。
<a onclick="myfunc(1)">test</a>
<a onclick="myfunc(2)">test</a>
<a onclick="myfunc(3)">test</a>
...........................但是很奇怪,为什么最后每个A结点的参数都是循环最后一次的值100呢?
<a onclick="myfunc(100)">test</a>
<a onclick="myfunc(100)">test</a>
<a onclick="myfunc(100)">test</a>
...........................
<a onclick="myfunc(100)">test</a>麻烦大家了。谢谢!
<script language=javascript>
function test()
{
for(var i=1;i<100;i++)
{
var a = document.createElement("a");
var txt = document.createTextNode("test");
a.appendChild(txt);
a.setAttribute("onclick",new function ()
{
return function()
{myfunc(i);}
});
var xx = document.getElementById('xx');
xx.appendChild(a);
}
} function myfunc(str)
{
alert(str+ ": ");
}
</script>
<body>
<input type=button value=test onclick= "test() "> <br>
<table id="tb" width=200 border=1>
<tr> <td bgcolor=yellow> 1111111111 </td> </tr>
</table>
<table width="760" border="0">
<tbody>
<tr>
<td id="xx"> </td>
<td> </td>
</tr>
</tbody>
</table>
</body>
</html> 动态生成结点A并给每个结点追加一个方法,
我希望每个A结点的onclick方法的参数都是外部循环的值,也就是这里的i值。
<a onclick="myfunc(1)">test</a>
<a onclick="myfunc(2)">test</a>
<a onclick="myfunc(3)">test</a>
...........................但是很奇怪,为什么最后每个A结点的参数都是循环最后一次的值100呢?
<a onclick="myfunc(100)">test</a>
<a onclick="myfunc(100)">test</a>
<a onclick="myfunc(100)">test</a>
...........................
<a onclick="myfunc(100)">test</a>麻烦大家了。谢谢!
for(var i=1;i<100;i++)
{
var a = document.createElement("a");
a.onclick=myfunc.bind(null,i);
}
a.setAttribute("onclick",
newfunction (i) {return function()
{myfunc(i);}
}(i));