【问题标题】:JQuery attach event to method in instanceJQuery将事件附加到实例中的方法
【发布时间】:2010-11-26 22:51:35
【问题描述】:

我的代码看起来像这样......

function Finder(id) {
            this.id = id;
            this.input = $("#" + this.id + " :input[type='text']:first")[0];
            $(this.input).bind('keyup'....);



            this.KeyUpHandler = function (e) { ..the event should trigger this.. }

this.input = 在“id”中找到的第一个输入类型元素,这就是我将要引用的内容。这可以满足我的需要。

然后我想要做的是在“输入”上绑定 keyup 事件。但是我希望事件引用我的函数中包含的实例方法 - this.KeyUpHandler()。

如果我刚刚在输入的标记上执行此操作(onkeypress="keyuphandler();"),我还需要将“e”作为已传递给函数的事件。

有什么想法可以将事件绑定到我正在使用的函数实例中的函数吗?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:
    function Finder(id) {
      this.id = id;
      this.input = $("#" + this.id + " :input[type='text']:first")[0];
      that=this;
      this.KeyUpHandler = function (e) { ..the event should trigger this.. }
      $(this.input).bind('keyup', this.KeyUpHandler);
    }
    

    在定义函数之后调用bind()很重要!

    【讨论】:

    • 这是正确的方向。然而,在我的 KeyUpHandler 函数中,'this' 现在是 Jquery 所知道的,而不是我引用成员变量的一种方式。因此,当我尝试使用 this.input 来引用我最初设置的内容时,我的函数中出现了一个未定义的错误。
    • 为了澄清上述内容,JQuery 已将“this”设置为触发事件的元素。我丢失了对成员变量的引用。
    • @RemotecUk:编辑了我的答案。现在尝试在事件处理程序中使用that 而不是this。有用吗?
    • 完美运行!我用 var ref = this; (但它是同一件事)。
    【解决方案2】:
      this.KeyUpHandler = function (e) { ..the event should trigger this.. } 
         $(this.input).bind('keyup', function(){
              this.KeyUpHandler(event);
             //more code can go here
          });
    

    【讨论】:

    • 你没有通过e。此外,这个包装函数看起来不太美观。
    • 是的。每个侦听事件的函数都会在第一个参数中获取有关事件的附加信息(在 IE 中除外,它们的做法有点丑陋)。通常,此参数的名称为e
    • 传递事件关键字应该这样做
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 2016-05-27
    • 2012-05-22
    • 1970-01-01
    相关资源
    最近更新 更多