[英]How to make an onlick event handler as a class method
我想創建一個具有onclick事件處理程序作為方法的JavaScript類:
<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>
但是我收到范圍錯誤: Uncaught ReferenceError:未定義clicked 。
為什么? 如何固定范圍並將事件處理程序保留為類的方法?
將按鈕創建為對象,然后直接分配點擊處理程序:
<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>
以這種方式進行操作可以直接引用函數本身,因為它始終在作用域內。 通過onclick
屬性對其進行分配,將失去聲明位置的范圍。
您可以通過直接鏈接到函數來避免這種情況:
$('#container').html('<button>Press</button>').find('button').click(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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.