开发者

Event handler cannot access Object method in JavaScript

开发者 https://www.devze.com 2022-12-19 19:08 出处:网络
How can I access util.log() method from a stat开发者_如何学编程ic html event handler? In other words, when I click the checkbox, I like to call util.log method.

How can I access util.log() method from a stat开发者_如何学编程ic html event handler?

In other words, when I click the checkbox, I like to call util.log method.

onclick="util.log(\'hey\')" <-- how to rewrite the event function here?

I know all the answers are correct down here but is it possible to access local methods while insert the html into innerHTML?

thank you

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. 
};


Your util object is not in the global scope; it's hidden inside the utilities object. The click handler will run in the scope of the global object, which is why it can't see util at all.

If you can't change the way the HTML strings are created, then you'll need to declare util outside the utilities function, in other words, just this in the page:

 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


try this javascript instead:

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

精彩评论

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