我有一个表单,如果用户更改平台(操作系统),则调用ajax调用并以json格式检索可用模型。我可以得到ajax调用以及我正确地将数据格式化,但我无法让模型下拉以使用新值(json值对)进行更新。我没有ID,因为有些行是动态添加的,所以我需要回复使用.next(),。find()等项目来遍历DOM,而我对此并不是很好。< / p>
以下是表格:
<div class="field inline">
<label class="frmFlds_labels">Platform</label>
<select name="platform" onChange="updateModels(this,18);" class="platform">
<option value=""></option>
<option value="IBM" selected="selected">AIX</option>
<option value="HP">HP-UX</option>
<option value="LINUX">Linux</option>
<option value="SUN">Solaris</option>
<option value="WINTEL">Wintel</option>
<option value="Other">Other</option>
</select>
</div>
<div class="field inline" platform="IBM">
<label class="frmFlds_labels">Model</label>
<select name="model" class="model">
<option value=""></option>
<option value="LPAR on p550">LPAR on p550</option>
<option value="LPAR on p561">LPAR on p561</option>
<option value="LPAR on p570">LPAR on p570</option>
</select>
这是JS代码:
function updateModels(i,id){
var pltfrm = $(i).val();
var firstOption = $(this);
$.getJSON("index.cfm?do=misc.getModels&platform=" + pltfrm,
function(j){
var options = '';
for (var i = 0; i < j.length; i++){
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
}
firstOption.next().children('.model').html(options);
});
}
答案 0 :(得分:1)
假设遍历是来自select的更改处理程序而firstOption是select,则需要转到parent()然后next()
firstOption.parent().next().children('.model').html(options);
答案 1 :(得分:0)
如果您更改布局,只需从标记中删除代码:
我添加了自定义属性:data-id
<div class="field inline">
<label class="frmFlds_labels">Platform</label>
<select name="platform" data-id="18" class="platform">
<option value=""></option>
<option value="IBM" selected="selected">AIX</option>
<option value="HP">HP-UX</option>
<option value="LINUX">Linux</option>
<option value="SUN">Solaris</option>
<option value="WINTEL">Wintel</option>
<option value="Other">Other</option>
</select>
</div>
<div class="field inline" platform="IBM">
<label class="frmFlds_labels">Model</label>
<select name="model" class="model">
<option value=""></option>
<option value="LPAR on p550">LPAR on p550</option>
<option value="LPAR on p561">LPAR on p561</option>
<option value="LPAR on p570">LPAR on p570</option>
</select>
</div>
然后使用它:
function updateModels(p, id) {
var firstOption = $(p);
var pltfrm = firstOption.val();
var model = firstOption.parent().next().find('.model');
$.getJSON("index.cfm?do=misc.getModels&platform=" + pltfrm, function(j) {
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
}
model.html(options);
});
}
$('.platform').change(function() {
var id = $(this).attr('data-id');
updateModels($(this), id);// I do not see you using the id but...
});
编辑:如果动态添加到页面中,代码不同:
$(document).on('change','.platform', function() {
var id = $(this).attr('data-id');
updateModels($(this), id);// I do not see you using the id but...
});