jQuery $.proxy() 方法

  遇到的问题:this 指针的指向。

  例:下列代码中第三行的 this指向button,而非panel。

$('#panel').fadeIn(function(){
    $('#panel button').click(function(){
        $(this).fadeOut();
    });
});

  解决方法:

  ①

$('#panel').fadeIn(function(){
    var that = this; //将这里指向 #panel 的this 存储为that
    $('#panel button').click(function(){
        $(that).fadeOut();
    });
});

  ② $(selector).proxy(function,context) 方法

$('#panel').fadeIn(function(){
    // 使用$.proxy :
    $('#panel button').click($.proxy(function(){
        // this 指向 #panel
        $(this).fadeOut();
    },this));
});

  ③ 另一种例子 $(selector).proxy(context,fn_name) 方法 —— (fn_name函数必须是前一个参数 ‘context’ 对象的属性)

 

var objPerson = {
   name: "John Doe",
   age: 32,
   test: function(){
     $("p").after("Name: " + this.name + "<br> Age: " + this.age);
   }//这里的test 是objPerson对象的一个方法
 };
$("button").click($.proxy(objPerson,"test"));

 

posted @ 2017-08-07 22:30  hiker90  阅读(300)  评论(0编辑  收藏  举报