【问题标题】:Event handler cannot access Object method in JavaScript事件处理程序无法访问 JavaScript 中的 Object 方法
【发布时间】:2023-04-04 21:36:01
【问题描述】:

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

【问题讨论】:

  • 您是否希望在单击复选框时发出“嘿”的提示?
  • 是的,但最终,如何从硬编码事件中调用对象方法?

标签: javascript events object methods


【解决方案1】:

您的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

【讨论】:

    【解决方案2】:

    试试这个 javascript:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-10
      • 2016-07-05
      • 2011-04-24
      相关资源
      最近更新 更多