gpt4 book ai didi

javascript - Uncaught ReferenceError 。在 jQuery 事件处理程序中找不到原型(prototype)函数

转载 作者:行者123 更新时间:2023-11-30 08:52:56 33 4
gpt4 key购买 nike

当我按下提交按钮时出现以下错误:

Uncaught ReferenceError: addText is not defined 
  • 为什么'click'处理函数找不到类原型(prototype)函数'addText'?

  • 我该怎么做才能解决这个问题?

  • 如果这是一种糟糕的事件处理方式? (我有 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。提前致谢!

编辑

这是我学到的东西:

  • “click”处理函数找不到函数“addText”,因为“this”不再引用类实例,而是引用事件的发送者。

  • 要解决这个问题,我应该将当前的“this”作用域保存在处理函数之外的变量中。

  • 我不确定以这种方式处理事件是否是一种不好的做法,但它确实有效,所以我将采用它。

  • 此外,我应该使用“on”而不是“bind”,因为“bind”似乎无论如何都会调用“on”。

感谢大家的快速回复!

最佳答案

试试这个:

MyClass.prototype.listenToButton = function(btn) {
var that = this;
$(btn).bind({
click: function(event) {
that.addText($(this).parent());
}
});
};

关于javascript - Uncaught ReferenceError 。在 jQuery 事件处理程序中找不到原型(prototype)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16173244/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com