如何从静态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.
};
答案 0 :(得分:2)
您的util
对象不在全球范围内;它隐藏在utilities
对象中。点击处理程序将在全局对象的范围内运行,这就是它根本看不到util
的原因。
如果您无法更改HTML字符串的创建方式,那么您需要在util
函数之外声明utilities
,换句话说,只需在页面中声明:
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
答案 1 :(得分:1)
试试这个javascript:
var util = {
log : function(msg){
alert(msg);
};
};