I’m building a jQuery plugin.
Calling the plugin
$('#box').jQueryPlugin({user:'user123'});
JQUERY PLUGIN
(function($){
$.fn.jQueryPlugin= function(options) {
var
defaults = {
user: ''
}
var options = $.extend(defaults, options);
var o = options;
$.ajax({
type: "get",
url: "http://api.domain.com/user/"+o.user,
data: "",
dataType: "jsonp",
success: function(data){
var p = data;
console.log(p.location);
$(this).html(p.location);
}
});
// returns the jQuery object to allow for chainability.
return this;
}
})(jQuery);
If I were to use the above, the console.log would show an error that it couldn’t write the p.location inside the div with id=”box”
How would I be able to get it so that it can write to whichever div is specified when calling the plugin?
thiswon’t have the context you expect in thesuccesscallback, so you just need to assign yourdivto a var so you can use it later..Another method would be to set the
contextoption in the$.ajaxcall, see the context option in the jQuery docs.