How to return $(this)

限于喜欢 提交于 2019-12-24 10:34:40

问题


I'm using jQuery and made a plugin for some in house work that basically builds URLs for our internal API. Anyways, I want to return $(this) and im not getting the right thing and im getting a createdocumentfragment error?

Plugin code:

$.get(base_url,{
    agenda_id:defaults.id,
    action:defaults.action+defaults.type,
    output:defaults.output
},function(html){
    defaults.callback(html);
});

That works fine, but i want to add return obj like so:

$.get(base_url,{
    agenda_id:defaults.id,
    action:defaults.action+defaults.type,
    output:defaults.output
},function(html){
    defaults.callback(html);
    return obj;
});

Obj is set at the start of my plugin and obj works fine throughout the plugin. It's set as obj=$(this);

In my script, which uses the plugin, I have:

$('#agenda-live-preview').agenda({action:'get',type:'agenda',id:window.location.href.split('/').pop(),callback:function(html){
    $(this).empty().append($(html).html());
}});

However, it doesn't work and returns:

Error: doc.createDocumentFragment is not a function
Source File: http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js
Line: 4373

In the console error logs. Any ideas how to return $(this) AND run the callback?


回答1:


I (finally) left a comment in your other question. :o) I'm pretty sure you need to do this in your plugin:

defaults.callback.call(this,html);

instead of:

defaults.callback(html);



回答2:


It sounds like you want to return the object to the original caller.

agenda = function(opts, callback) {
    $.get(base_url,{
        agenda_id:defaults.id,
        action:defaults.action+defaults.type,
        output:defaults.output
    },function(html){
        defaults.callback(html);
    });

    return obj;
}

I'm guessing the idea is to enable chaining, so that you can say something like

$('#id').agenda(opts).show();

or whatever. Of course, this will execute just after the $.get is issued and not after it is completed, but this is normal and probably what you want.



来源:https://stackoverflow.com/questions/3048190/how-to-return-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!