【问题标题】:Can i pass a function returned data to jquery on() event?我可以将函数返回的数据传递给 jquery on() 事件吗?
【发布时间】:2012-11-24 13:21:12
【问题描述】:

这是我的代码

var addproduct = {
    init:function(){
        var footer = $("<div class='footer'></div>");
        var confirmButton = $("<button class='dbtn'>confirm</button>").on('click',this.confirm);
        var cancelButton = $("<button class='dbtn'>cancel</button>").on('click',this.cancel);
        d.append(footer.append(confirmButton,cancelButton));

        $('body').append(d)
    },

    getData:function(){
        var data={};
        d.find('#basic_info :input').each(function(){
            data[$(this).attr('name')] = $(this).val()
        });
        console.log(data);
        return data;
    },

    confirm:function(e){

        console.log(e.data);
    },

    cancel:function(){
        alert(2);
    }

}

当我点击确认按钮时,我想在“d”中提交表单,所以我想使用“getData”函数来获取所有表单数据,

这就是我所做的

var confirmButton = $("<button class='dbtn'>confirm</button>").on('click',this.getData,this.confirm);

//output: function()

所以我猜传递给处理程序的数据不能是一个函数吧???

然后我像这样更改确认功能

confirm:function(){

     var data = this.getData()
     console.log(data);
    },

 this will not work too , because the 'this' keyword is not the addproduct object,but the confirm button '<button>confirm</button>';

那么我怎样才能将getData函数的返回数据传递给confirm函数??????

为什么“this”不是 addproduct 对象???

【问题讨论】:

    标签: javascript jquery events


    【解决方案1】:

    试试

    var confirmButton = $("<button class='dbtn'>confirm</button>")
                         .on('click',this.getData(),this.confirm);
    

    getData 返回您要传递给事件处理程序的数据对象,因此您必须实际调用该函数。那么这里应该可以看到数据了

    confirm:function(e){
    
        console.log(e.data);
    },
    

    【讨论】:

    • 顺便说一下为什么'this'关键字不是addproduct对象而是按钮
    • @chenliang from api.jquery.com/on When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector. (Note that this may not be equal to event.target if the event has bubbled from a descendant element.) To create a jQuery object from the element so that it can be used with jQuery methods, use $(this).
    • 如果我想在确认中调用addproduct对象的另一个方法怎么办?
    • 我试试这个确认:function(e,this){ console.log(this); },它不起作用,这意味着我只能将一个参数传递给处理程序
    • @chenliang 试试.on('click',[this.getData(), this],this.confirm);
    猜你喜欢
    • 1970-01-01
    • 2014-08-07
    • 2016-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    相关资源
    最近更新 更多