首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > asp.net >

动态平添onclick事件不起效果

2012-12-16 
动态添加onclick事件不起效果script typetext/javascriptfunction initselect() {var td document.

动态添加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'>
    
        <table>


            <tr>
                <td id='best'>
                    A
                </td>
                <td>
                    B
                </td>
                <td>
                    C
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>


[其他解释]
你创建的这个元素是不是没有放到页面上啊
[其他解释]
漏了一句在function initselect() 中的,加上div.innerHTML=“最优值";
而且页面上能实现initselect()中的其他属性的添加,比如我加入div.style.cursor="pointer"是有效果的,唯独这个onclick不起作用!
[其他解释]
而且我如果把div.onclick=function(){ShowDiv('MyDiv');}
改为div.onclick=ShowDiv('MyDiv');的话,浏览页面的时候直接出现了我隐藏的层,点击事件不起作用
[其他解释]
看看 jquery的 demo吧
[其他解释]
对了同学,需要显示元素的时候千万不要用  style.display='block' ,用style.display=''就可以了,以后要记住啦!
[其他解释]
var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.backgroundColor = "red";
div.innerHTML="最优值";
div.onclick=function(){showMessage("hdh");}
document.body.appendChild(div);

function showMessage(msg) {
alert(msg);
}
[其他解释]
5楼的attachEvent这个函数对我有用处,这样省的我用字符串拼接的方式实现了

热点排行