-3

我有以下代码:

<script>
jQuery(document).ready(function ($) {
  'use strict';
  var Image_Selector = function () {};

  Image_Selector.prototype.init = function ($wrapper) {
    this.$select_btn = $wrapper.find('.set-image-btn');

    this.$select_btn.click(function (e) {
      console.log(this);    //jquery object
      console.log(e);       //just the event

      // What's the best way to call 'open_image_selector()' here?
    });
  }; // init

  Image_Selector.prototype.open_image_selector = function () {
    console.log (this);
    // do awesome stuff
  };
}); // doc rdy
</script>

open_image_selector在函数内部调用的最佳方法是jquery.click什么?

4

2 回答 2

1

this在 clcik 处理程序中是被单击的 DOM 元素。

this在 clcik 处理程序之外缓存您的类,以便它在处理程序内可用。也可以$.proxy用于更改处理程序的上下文

Image_Selector.prototype.init = function ($wrapper) {

     var self=this;
    self.$select_btn = $wrapper.find('.set-image-btn');

    self.$select_btn.click(function (e) {
      console.log(self); /* should log "Image_Selector" object*/
       self.open_image_selector()  

    });
  }; // init
于 2013-03-30T11:06:30.943 回答
1

使用bind方法

 this.$select_btn.click(function (e) {
    console.log(this);
    console.log(e);
    //Calling `open_image_selector`
    this.open_image_selector()
 }.bind(this)); 

绑定this到您的单击侦听器,以便this在该函数内部引用对象的当前实例Image_Selector

于 2013-03-30T11:19:27.100 回答