日期:2014-05-17  浏览次数:20493 次

动态添加onclick事件不起效果
<script type="text/javascript">
function initselect() {
var td = document.getElementById("best");
        var div = document.createElement("div");
div.onclick=function(){ShowDiv('MyDiv');}
}
//弹出隐藏层
function ShowDiv(show_div){
document.getElementById(show_div).style.display='block';
};
//关闭弹出层
function CloseDiv(show_div)
{
document.getElementById(show_div).style.display='none';
};
</script>

加td的属性为onclick点击事件的为什么不起效果?best为<td>的id
MyDiv为一个<div>层的id
------最佳解决方案--------------------
这位同学确实可爱,在你的代码中,我没看到你给td添加事件,我直接帮你写了一个:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
        function js_createElement(){
            var div = document.createElement('div');
            div.innerHTML='test';
            div.id = 'div_2';
              div.onclick=function(){
                alert(1);
              }
            
            document.getElementById('div1').appendChild(div);
        }
        window.onload = bestTd;
        function bestTd(){
            var best = document.getElementById('best');
            js_createElement();
            best.attachEvent('onclick',function(){
               var div_2 = document.getElementById('div_2');
               if(!!div_2){
                    if(div_2.style.display=='')
                        div_2.style.display='none';
                    else
                        div_2.style.display='';
               }
            });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id='div1'>
 &nb