My case:
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();
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
, eg: 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.