Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/452.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用jQuery将构造函数方法附加为处理程序_Javascript - Fatal编程技术网

Javascript 使用jQuery将构造函数方法附加为处理程序

Javascript 使用jQuery将构造函数方法附加为处理程序,javascript,Javascript,所以,我有这个: function foo(){ var that = this; this.elements = [ $bar = $('.bar'), $foo = $('.foo') ]; this.example = function(){ alert("a"); } this.elements.$bar.on('click', that.example); } 但是,如果我改变这一行,它就不起作用了: this.elemen

所以,我有这个:

function foo(){

  var that = this;

  this.elements = [
    $bar = $('.bar'),
    $foo = $('.foo')
  ];

  this.example = function(){
    alert("a");
  }

  this.elements.$bar.on('click', that.example);
}
但是,如果我改变这一行,它就不起作用了:

  this.elements.$bar.on('click', that.example);
对于这一个:

  this.elements.$bar.on('click', function(){ that.example() });
也就是说,将方法包装到匿名函数中,它确实有效


编辑:如果方法不在构造函数中,它也可以工作。

我认为在当前代码中附加方法的方式没有问题。虽然我注意到您这样调用DOM元素:

this.elements = [
    $bar = $('.bar'),
    $foo = $('.foo')
];

this.elements.$bar
相反,请尝试将其指定为对象:

this.elements = {
    $bar : $('.bar'),
    $foo : $('.foo')
 };
然后在代码中:

this.elements.$bar.on('click', that.example);
下面是一个示例JSFIDLE,以了解更多详细信息:


希望这对您有所帮助

哦,我想出来了,事件附件必须在方法之后,否则它是未定义的,jQuery会忽略它,并且不会抛出任何错误。如果您愿意,请编辑您的答案,以便对将来可能有相同问题的其他人有用。