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

发布于 2024-08-20 16:47:47 字数 635 浏览 5 评论 0原文

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

How can I access util.log() method from a static 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. 
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一袭白衣梦中忆 2024-08-27 16:47:48

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

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

 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

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
书间行客 2024-08-27 16:47:48

试试这个 JavaScript:

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

try this javascript instead:

var util = {
 log : function(msg){
  alert(msg);
 };
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文