Javascript 如何将onlick事件处理程序作为类方法

Javascript 如何将onlick事件处理程序作为类方法,javascript,Javascript,我想创建一个JavaScript类,该类将onclick事件处理程序作为方法: <html> <head> <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script> <script> $(document).ready(function () { var foo = new Foo(); foo.load(); }); function Foo() {

我想创建一个JavaScript类,该类将onclick事件处理程序作为方法:

<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function () {
  var foo = new Foo();
  foo.load();
});
function Foo() {
  function clicked() {
    alert('clicked');
  }
  this.load = function () {
    $('#container').html('<button onclick="clicked()">Press</button>');  
  }
}
</script>
</head>
<body>
  <div id="container"></div>
</body>
</html>

$(文档).ready(函数(){
var foo=new foo();
foo.load();
});
函数Foo(){
函数单击(){
警报(“点击”);
}
this.load=函数(){
$('#container').html('Press');
}
}
但是我得到了一个范围错误:未捕获引用错误:单击未定义


为什么??如何修复范围并将事件处理程序保留为类的方法?

将按钮创建为对象,并直接分配单击处理程序:

<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function () {
  var foo = new Foo();
  foo.load();
});
function Foo() {
  function clicked() {
    alert('clicked');
  }
  this.load = function () {
    var b = $('<button>');
    b.text('Press');
    b.on('click', clicked);
    $('#container').append(b);  
  }
}
</script>
</head>
<body>
  <div id="container"></div>
</body>
</html>

$(文档).ready(函数(){
var foo=new foo();
foo.load();
});
函数Foo(){
函数单击(){
警报(“点击”);
}
this.load=函数(){
var b=$('');
b、 文本(“新闻”);
b、 打开(“单击”,单击);
$(“#容器”)。附加(b);
}
}

这样做可以直接引用函数本身,因为它总是在作用域中。通过
onclick
属性分配它,它将失去声明它的范围。

您可以通过直接链接到函数来避免这种情况:

$('#container').html('<button>Press</button>').find('button').click(clicked);
$('#container').html('Press')。查找('button')。单击(clicked);
试试这个

<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function () {

        foo.load();
});
var foo = new Foo();
function Foo() 
{
this.clicked=clicked;
function clicked() 
{
        alert('clicked');
}

this.load = function () 
{
        $('#container').html('<button onclick="foo.clicked();">Press</button>');  
}
}
</script>
</head>
<body>
  <div id="container"></div>
</body>
</html>

$(文档).ready(函数(){
foo.load();
});
var foo=new foo();
函数Foo()
{
this.clicked=单击;
函数单击()
{
警报(“点击”);
}
this.load=函数()
{
$('#container').html('Press');
}
}