我有一个类 Foo,它有一个生成显示 HTML 的方法。我希望 HTML 有一个onclick
事件处理程序,它调用Foo.clickHandler
. 问题是我不知道这个特定实例的Foo
名称是什么。同样,onclick
事件无法知道如何访问Foo
. 这是一些代码:
function Foo(){
this.nonStaticVariable='Something non-static (different for every instance of Foo).';
this.getHTML=function(){
return '<a href="javascript:void(0);" onclick="/* How do I call Foo.clickHandler? */">Click Me!</a>';
}
this.clickHandler=function(){
alert(nonStaticVariable);
}
}
非静态函数的要点是表明onclick
需要调用正确的实例Foo
。
我曾考虑过将一个字符串传递给Foo
包含包含的变量名Foo
,但这似乎是反 OOP:
function Foo(container){
this.container=container;
this.nonStaticVariable='Something non-static (different for every instance of Foo).';
this.getHTML=function(){
return '<a href="javascript:void(0);" onclick="'+container+'.clickHandler();">Click Me!</a>';
}
this.clickHandler=function(){
alert(nonStaticVariable);
}
}
var fooInstance=new Foo('fooInstance');
你有什么建议?
我也对 jQuery 解决方案持开放态度。