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"));

 

转载于:https://www.cnblogs.com/hiker90/p/7301740.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值