动态添加 带参数 事件 的问题

microsy 2007-12-06 03:14:41
想在页面加载后为某个TABLE的每一个td添加onclick事件处理,
在HTML里直接嵌函数时没有什么问题.
但是动态时遇到一些问题,添加完后运行时,
在每一个TD中click都会显示最后一个TD的内容,不知道是哪里
的事件绑定给覆盖了? 以下是代码,多谢.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script language="JavaScript" type="text/javascript">
function init()
{
var table = document.getElementById("table1");
var trlen = table.rows.length;
var tdlen = table.rows[0].cells.length;

for (row=0; row < trlen; row++)
{
for (col=0; col < tdlen; col++)
{
ttt = table.rows[row].cells[col];
ttt.attachEvent("onclick",function(){ selcol(ttt) });
}
}
}
function selcol(td)
{
alert(td.innerHTML);
//其他代码......
}
</script>
</head>

<body onload="init();">
<table id="table1" width="200" border="1">
<tr>
<td>a</td>
<td>aa</td>
</tr>
<tr>
<td>b</td>
<td>bb</td>
</tr>
</table>
</body>
</html>

...全文
224 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
microsy 2007-12-08
  • 打赏
  • 举报
回复
闭包问题,已解决,多谢,结贴~
Clark21 2007-12-06
  • 打赏
  • 举报
回复
要注意變量的作用域就可以。
iori_wen 2007-12-06
  • 打赏
  • 举报
回复
这种问题调试下就迎刃而解了,我刚学javascript二个星期,用VS.net2008解决一切像楼主这样的问题~
s_liangchao1s 2007-12-06
  • 打赏
  • 举报
回复
楼上正解 楼主的ttt当循环添加onclick后就一直是2了
mingxuan3000 2007-12-06
  • 打赏
  • 举报
回复
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无??文档</title>
<script language="JavaScript" type="text/javascript">
function init()
{
var table = document.getElementById("table1");
var trlen = table.rows.length;
var tdlen = table.rows[0].cells.length;

for (row=0; row < trlen; row++)
{
for (col=0; col < tdlen; col++)
{
(function (x,y){var ttt=table.rows[x].cells[y];ttt.attachEvent("onclick",function(){ selcol(ttt) })})(row,col)

}
}
}
function selcol(td)
{
alert(td.innerHTML);
//其他代?......
}
</script>
</head>

<body onload="init();">
<table id="table1" width="200" border="1">
<tr>
<td>a</td>
<td>aa</td>
</tr>
<tr>
<td>b</td>
<td>bb</td>
</tr>
</table>
</body>
</html>

87,910

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧