我有这个HTML结构:
<div class="row">
<div class="col-sm-6 p-l-0">
<div class="form-group form-group-default form-group-default-select2 required">
<select disabled class="kurir">
<option select="selected"></option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group form-group-default form-group-default-select2 required">
<select disabled class="tarif">
<option select="selected"></option>
</select>
</div>
</div>
</div>
这是我的javascript:
$(".kurir").change(function() {
var json_url = "some url here";
$.getJSON( json_url, function( data ) {
var tarif_items = "";
$.each( data, function( key, val ) {
tarif_items += "<option value='" + key + "'>" + val + "</option>";
alert (key); // I can see the key value
alert (val); // I can see the val value
});
});
$(this).closest(".row").find(".tarif").css("background-color", "red"); // I can see there's background color
$(this).closest(".row").find(".tarif").prop("disabled", false); // I can see the select is active now
$(this).closest(".row").find(".tarif").append(tarif_items); // but I don't see this works, why?
});
为什么tarif_items
无法附加到select元素中?
答案 0 :(得分:2)
这是因为tarif_items
未在getJSON
方法之外定义。即使你全局定义它,它的值也将通过异步调用来设置。这不会反映在.append()
电话中。正确的方法是:
$(".kurir").change(function() {
var json_url = "some url here";
var _thattarif = $(this).closest(".row").find(".tarif");
$.getJSON( json_url, function( data ) {
$.each( data, function( key, val ) {
alert (key); // I can see the key value
alert (val); // I can see the val value
_thattarif.css("background-color", "red");
_thattarif.prop("disabled", false);
_thattarif.append("<option value='" + key + "'>" + val + "</option>");
});
});
});