在私有函数中设置事件监听器

问题描述

| 我的情况 :
    function C() {
            this.create = function() {
                    var div=document.createElement(\"div\");
                    div.setAttribute(\"onclick\",\"alert(\'this works\')\");
                    div.onclick=function(){
                            alert(\"this doesnt work\");
                    }
                    document.appendChild(div);
            }
            this.create();
    }
    var x = new C();
无法在javascript中以这种方式设置onclick事件? 应该对调用函数进行全局定义吗?我可以理解它不是全局定义的问题。但是我想在定义onclick事件的函数中使用私有变量。有什么建议么 ??????     

解决方法

        您发布的内容几乎是正确的。将元素附加到除
document
之外的任何内容上,例如:
document.body
。不要用
setAttribute
设置事件处理程序,因为它有问题。 您可以使用
onclick
属性或W3C标准
addEventListener
方法(IE中为
attachEvent
)。
function C() {
    this.create = function() {
        var div = document.createElement(\"div\");
        div.innerHTML = \"click me\";
        var inner = \"WORKS!\";
        div.onclick = function(){
            alert(inner); // private variable is ok
        };
        document.body.appendChild(div);
        div = null; // avoid memory leak in IE
    };
    this.create();
}
var x = new C();
    ,        关于什么
div.addEventListener(\'click\',function() {
    alert(\'hello!\');
},false);
? 这样,该函数是匿名的,并且仅在您声明它的范围内可见。这不是全球性的。 以下是有关addEventListener的一些API文档:https://developer.mozilla.org/en/DOM/element.addEventListener