繁体   English   中英

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

[英]Event handler cannot access Object method in JavaScript

如何从静态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. 
};

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

如果您无法更改HTML字符串的创建方式,则需要在utilities函数外部声明util ,换句话说,就是在页面中声明以下内容:

 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

试试这个JavaScript代替:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM