日期:2014-05-16  浏览次数:20303 次

不知道什么问题,动态创建div,事件失效?
做仿QQ邮箱的,我的做法是选择联系人以后,在收信人这栏里动态的创建div,然后把这个div加上onclick和ondblclick事件,只选收件人的时候,这个是没有问题的;然后,还有个抄送人,同上的做法,选择联系人,根据联系人的姓名和email在抄送人栏里创建div,这时候你发现也可以,但是,当你在回头看收信人的时候,你会发现它的onclick事件什么的都失效了,点了没反应,比较郁闷,嘛,上代码

var e_id= opts[i].value+field.substring(field.indexOf('_'),field.length);
var currDiv=document.createElement("div");
currDiv.setAttribute('id',e_id);//动态创建的div根据父级的div来生成id,所以id不会相同
currDiv.setAttribute("ondblclick",function(){window.parent.frames.openLookUpRefWin(this);return false;});
currDiv.setAttribute("onclick",function(){window.parent.frames.changeStatus(this)});
currDiv.setAttribute('url',url);
currDiv.style.cssText="margin-right:5px;height:15px;padding-top:5px;float:left;white-space:nowrap;clear:both;";
currDiv.innerHTML=opts[i].innerHTML+"<img src='_imgs/ico/x1_close.gif' width='10px' style='cursor:hand;' onclick=remove('"+e_id+"'); />";//img的onclick同样失效了
parent_node.insertBefore(currDiv,parent_node.getElementsByTagName('input')[0]);

琢磨了两天了,不知道啥问题,可能是我别的地方有问题,就这一块来说有问题吗?

------解决方案--------------------
currDiv.onclick
或者使用DOM事件模型注册事件
------解决方案--------------------
livequery
------解决方案--------------------
debug
------解决方案--------------------
改成这样试试

var e_id= opts[i].value+field.substring(field.indexOf('_'),field.length);
var currDiv=document.createElement("div");
currDiv.setAttribute('id',e_id);//动态创建的div根据父级的div来生成id,所以id不会相同
 
currDiv.ondblclick=function(){window.parent.frames.openLookUpRefWin(this);return false;}
currDiv.onclick=function(){window.parent.frames.changeStatus(this)}

currDiv.setAttribute('url',url);
currDiv.style.cssText="margin-right:5px;height:15px;padding-top:5px;float:left;white-space:nowrap;clear:both;";
currDiv.innerHTML=opts[i].innerHTML+"<img src='_imgs/ico/x1_close.gif' width='10px' style='cursor:hand;' onclick=remove('"+e_id+"'); />";//img的onclick同样失效了
parent_node.insertBefore(currDiv,parent_node.getElementsByTagName('input')[0]);