我收到以下錯誤,當我按下提交鍵:未捕獲的ReferenceError。原型函數沒有jQuery的事件處理中發現
Uncaught ReferenceError: addText is not defined
怎麼來的「點擊」處理功能無法找到類函數原型「添加文字'?
我能做些什麼來解決這個問題?
如果這是處理事件的不好方法? (我來自一個Java的背景,我與面向對象的JavaScript的最佳做法有點不確定)
下面是代碼:
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="js/jquery-1.9.1.js"></script>
<script>
//Class ctor
function MyClass() {
this.msg = "Hello World!";
}
//This method appends text to the given doc element
MyClass.prototype.addText = function(doc) {
$(doc).append('<br/>'+this.msg);
};
/*
* This method adds a 'click' listener to the given element which
* calls the 'addText' method on its parent.
*/
MyClass.prototype.listenToButton = function(btn) {
$(btn).bind({
click: function(event) {
addText($(this).parent());
}
});
};
$(document).ready(function() {
//Create instance of class
var c = new MyClass();
//Listen to button
c.listenToButton($("#mybutton"));
});
</script>
</head>
<body>
<div>Button: <input id="mybutton" type="button" value="Submit"></div>
</body>
顯然我使用jQuery。提前致謝!
編輯
這是我學到的:
的「點擊」處理功能無法找到函數「addText」,因爲「這」不再引用的類的實例,但事件的發送者。
要解決這個問題,我應該將當前'this'作用域保存在處理函數外部的變量中。
我不確定以這種方式處理事件是否是不好的做法,但它起作用,所以我要去用它。
此外,我應該使用'on'而不是'bind',因爲它看起來像'綁定'調用'反正'。
感謝大家的快速回復!
您應該使用'on',而不是'bind'。你需要了解'this'的範圍。 – epascarello 2013-04-23 15:27:55
基本上,在click事件中,上下文('this')不再是MyClass的實例,它是被單擊的元素*,因此addText沒有被定義。 – 2013-04-23 15:28:21
@epascarello好的,有什麼區別? – souldzin 2013-04-23 15:28:54