事件处理程序无法访问JavaScript中的Object方法

时间:2010-02-05 02:23:35

标签: javascript events object methods

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

换句话说,当我单击复选框时,我想调用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. 
};

2 个答案:

答案 0 :(得分:2)

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

如果您无法更改HTML字符串的创建方式,那么您需要在util函数之外声明utilities,换句话说,只需在页面中声明:

 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 :(得分:1)

试试这个javascript:

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