捕获原型函数内的键码

发布于 2024-08-10 14:12:59 字数 524 浏览 1 评论 0原文

我正在尝试在原型函数中捕获击键。

这是我的代码:

function txtBox(input) // pass textbox
{
     this.id = "myTextbox";
     this.txt = input
}
txtBox.prototype.init = function()
{
     this.txt.bind("keyup",this.keyup);
}
txtBox.prototype.keyup= function(event)
{
     alert("keycode: event.keyCode);
     alert(this.id);
}
var myTxt = new txtBox($(#txt)); // create object
myTxt.init();

捕获有效,但问题是 keyup 在我的对象“外部”触发,这意味着 this.id 返回“未定义”,即使它定义。

有谁知道如何保持一致性?

I'm trying to capture keystrokes inside my prototype function.

Here's my code:

function txtBox(input) // pass textbox
{
     this.id = "myTextbox";
     this.txt = input
}
txtBox.prototype.init = function()
{
     this.txt.bind("keyup",this.keyup);
}
txtBox.prototype.keyup= function(event)
{
     alert("keycode: event.keyCode);
     alert(this.id);
}
var myTxt = new txtBox($(#txt)); // create object
myTxt.init();

Capturing works but the problem is that the keyup triggers "outside" my object, which means this.id returns "undefined" even though it was defined.

Does anyone know how to keep consistency with this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

煮酒 2024-08-17 14:12:59

我尝试将您的代码复制粘贴到我的萤火虫中并在此页面上运行它(尽管将警报更改为console.log)。而且看起来效果很好。它捕获我选择的文本字段中的每个按键,但不捕获其他任何地方。

I tried copy pasting your code into my firebug and running it on this page (changed the alerts to console.log though). And it seems to work just fine. It captures every keydown in the textfield I selected, but not anywhere else.

终止放荡 2024-08-17 14:12:59

我看到两个问题,假设您的脚本中有一个名为 "txt" 的实际标签,如下所示:

<input type="text" id="txt"/>

此行需要从 更改为

alert("keycode: event.keyCode);

alert("keycode": event.keyCode);

需要从 更改为

new txtBox($(#txt)); 

new txtBox($('#txt')); 

它会提醒您的文本框name,我不相信在 IE 中,您将能够按照您尝试更改 id 的方式来更改 id this.id="textbox"

Two problems I see, assuming you have an actual tag named "txt" in your script as so:

<input type="text" id="txt"/>

this line needs to be change from

alert("keycode: event.keyCode);

to

alert("keycode": event.keyCode);

also this needs to be changed from

new txtBox($(#txt)); 

to

new txtBox($('#txt')); 

and it will alert your textbox name, I dont believe in IE you will be able to change the id the way you're trying to change it doing this.id="textbox"

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文