2010-02-05 124 views
1

如何从静态html事件处理程序访问util.log()方法?事件处理程序无法访问JavaScript中的Object方法

换句话说,当我点击复选框时,我喜欢调用util.log方法。

onclick =“util.log(\'hey \')”< - 如何在这里重写事件函数?

我知道所有的答案在这里是正确的,但是可以在插入html到innerHTML的时候访问本地方法吗?

谢谢

var utilities = function() { 
var util = this; 

util.log = function(msg){ 
    alert(msg); 
}; 

var p = document.createElement('p'); 
p.innerHTML = '<input type="checkbox" onclick="util.log(\'hey\')" value="1">Check me'; 
// this part has to be plain html, because there is this table generator class 
// will insert this to cell as innerHTML. That's why I can't change the table class. 
}; 
+0

你想点击复选框时会显示“嗨”的提示? – 2010-02-05 02:30:35

+0

是的,但最终,如何从硬编码事件调用对象方法? – Nizzy 2010-02-05 02:32:45

回答

2

util对象不是在全球范围内;它隐藏在utilities对象内。点击处理程序将运行在全局对象的范围内,这就是为什么它根本看不到util

如果你不能改变被创建的HTML字符串的方式,那么你就需要声明utilutilities功能以外,换句话说,仅此页面:

var util = {}; 
util.log = function(msg){ 
    alert(msg); 
}; 

var p = document.createElement('p'); 
p.innerHTML = '<input type="checkbox" onclick="util.log(\'hey\')" value="1">Check me'; // this part is a legacy code and I have no control over to rewrite it as HTMLObjectElement way 
1

尝试这个JavaScript来代替:

var util = { 
log : function(msg){ 
    alert(msg); 
}; 
}; 
相关问题