I have a jQuery function called "bindServingSizes" which I call like this
$(servingsizes).bindServingSizes(i开发者_如何学JAVAngredientid);
Where "servingsizes" is a valid drop down list control.
jQuery.fn.bindServingSizes = function(ingredientid) {
$.getJSON("/serving_sizes?ingredientid=" + ingredientid, function(j) {
var options = "<option value=''>Please select a serving size</option>";
for (var i=0; i < j.length; i++)
options += '<option value="' + j[i].serving_size.id + '">' + j[i].serving_size.name + '</option>';
$(this).html(options);
});
};
I do get data back from the server and I am able to see what is in the "options" variable by displaying it on the page. However, I am not able to set the html contents to the element. What could I be missing?
Thanks
The problem is that $(this) in your callback function from $.getJSON is no longer the select box. Try this which creates a variable which stores the reference to the select box.
jQuery.fn.bindServingSizes = function(ingredientid) {
var $this = $(this);
$.getJSON("/serving_sizes?ingredientid=" + ingredientid, function(j) {
var options = "<option value=''>Please select a serving size</option>";
for (var i=0; i < j.length; i++)
options += '<option value="' + j[i].serving_size.id + '">' + j[i].serving_size.name + '</option>';
$this.html(options);
});
};
When you call $(this)
you call $.getJSON
object.
Add outside it some var container = $('containerId');
and execute conainer.html(opions);
精彩评论