事件处理程序无法访问 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.
};
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的 util 对象不在全局范围内;它隐藏在
utilities
对象内。点击处理程序将在全局对象的范围内运行,这就是它根本看不到util
的原因。如果您无法更改 HTML 字符串的创建方式,那么您需要在
utilities
函数外部声明util
,换句话说,只需在页面中声明 this :Your
util
object is not in the global scope; it's hidden inside theutilities
object. The click handler will run in the scope of the global object, which is why it can't seeutil
at all.If you can't change the way the HTML strings are created, then you'll need to declare
util
outside theutilities
function, in other words, just this in the page:试试这个 JavaScript:
try this javascript instead: