我有这个 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.push( "<option value='" + key + "'>" + val + "</option>" );
});
$(this).parent().parent().next().find('.tarif').append(tarif_items);
});
});
我可以从 JSON 数据中完美获取 key
和 val
,但为什么我在 .tarif
中仍然得到空选项?为什么 jquery 无法附加 tarif_items ?非常感谢。
最佳答案
它失败了,因为您试图附加一个 array
而不是 HTML string
。
要解决此问题:
var $this = $(this);
$.getJSON( json_url, function( data ) {
var tarif_items = "";
$.each( data, function( key, val ) {
tarif_items += "<option value='" + key + "'>" + val + "</option>";
});
$this.parent().parent().next().find('.tarif').append(tarif_items);
});
我还建议您向该选择添加一个id
属性,例如
<select id="tarif" disabled class="tarif">
<option select="selected"></option>
</select>
并像这样更改代码
// $this.parent().parent().next().find('.tarif').append(tarif_items);
$('#tarif').append(tarif_items);
最后,作为最后的改进。我建议您进行重置以避免进一步的问题:
HTML:
<select id="tarif" disabled class="tarif">
<!-- no default option -->
</select>
JS:
$.getJSON( json_url, function( data ) {
$('#tarif').html(''); // this resets the select content each time we receive the json
var tarif_items = "<option select="selected"></option>"; // here it goes
$.each( data, function( key, val ) {
tarif_items += "<option value='" + key + "'>" + val + "</option>";
});
$('#tarif').append(tarif_items);
});
这样您还可以多次调用该函数并重新生成选择。
关于javascript - jQuery 无法将 JSON 数据附加为选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36739529/