开发者

Setting eventlisteners in private functions

开发者 https://www.devze.com 2023-03-13 01:45 出处:网络
My case : function C() { this.create = function() { var div=document.createElement("div"); div.setAtt开发者_如何学Pythonribute("onclick","alert(\'this works\')");

My case :

function C() {
        this.create = function() {
                var div=document.createElement("div");
                div.setAtt开发者_如何学Pythonribute("onclick","alert('this works')");
                div.onclick=function(){
                        alert("this doesnt work");
                }
                document.appendChild(div);
        }
        this.create();
}
var x = new C();

Is it not possible to set onclick event that way in JavaScript? Should the function that is called should be globally defined? I can understand the problem that it is not globally defined, but I want to use the private variables within the function where I define the onclick event. Any suggestions?


What you've posted is almost correct. Append the element to anything but the document, e.g.: document.body. Don't set event handlers with setAttribute because it's buggy. You can use the onclick property or the W3C standard addEventListener method (attachEvent in IE).

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();


What about

div.addEventListener('click', function() {
    alert('hello!');
}, false);

?

That way the function is anonymous and is only seen in the scope in which you're declaring it. It's not global.

Here's some API docs on addEventListener: https://developer.mozilla.org/en/DOM/element.addEventListener

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号