将选项元素添加到选择失败

时间:2016-04-20 11:20:02

标签: javascript jquery

我有这个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元素中?

1 个答案:

答案 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>"); 
    });  
  });
});