js中怎么为每个创建的td添加onclick事件?

for (var i=0; i<size; i++){
var nextNode = the_names[i].firstChild.data;
row = document.createElement("tr");
cell = document.createElement("td");
//#FFFAFA
cell.onmouseout = function(){this.className='mouseOver';};
cell.onmouseover = function(){this.className='mouseOut';};
cell.setAttribute("bgcolor","red");
cell.setAttribute("border","1");
var self=this;
cell.onclick =function(){
alert('1111');
inputField.value = self.firstChild.nodeValue;
clearNames();
};

txtNode = document.createTextNode(nextNode);
cell.appendChild(txtNode);
row.appendChild(cell);
nameTableBody.appendChild(row);
}
这是我写的代码,为何那个“111” 总是不打印,求高手指点
是我失误了,其实这样是可以的,我只是在那个文本框中写了个onblur()事件,当点击那个单元格是触发这个onblur(),不会触发那个onclick事件.希望以后要注意了

直接在td中增加onclick属性。

过程:

1、定一个td的onclick函数

function TdClick(){//定义一个td的onclick函数
}

2、创建td,并添加onclick事件

var td1 = document.createElement('td');//创建一个td节点
td1.onclick=TdClick;//添加td的onclick函数

温馨提示:内容为网友见解,仅供参考
第1个回答  2011-08-08
改成这样子试试。
txtNode = document.createTextNode(nextNode);
cell.appendChild(txtNode);
row.appendChild(cell);
nameTableBody.appendChild(row);

cell.onmouseout = function(){this.className='mouseOver';};
cell.onmouseover = function(){this.className='mouseOut';};
cell.setAttribute("bgcolor","red");
cell.setAttribute("border","1");
var self=this;
cell.onclick =function(){
alert('1111');
inputField.value = self.firstChild.nodeValue;
clearNames();
};
第2个回答  2011-08-08
cell.setAttribute("id","cellid");

cellid onclick =function(){
alert('1111');
}
第3个回答  2011-08-08
把 html 和 JS 里面的 var 都贴出来本回答被提问者采纳
第4个回答  2011-08-08
不太清楚。
相似回答