这是我正确填充选择列表的内容:
<select id="countriesList">
<option value="0"> -- select country -- </option>
<option value="500"> 500 </option>
</select>
<script type="text/javascript">
$(function () {
// load the countries list
$.getJSON(
"/StaticData/GetAllCountries/",
function (countries) {
// iterate each returned country and add it to the countries select list.
$.each(countries, function (i, country) {
$("#countriesList").append("<option value='" + country.Id + "'>" + country.Description + "</option>");
});
});
// set the selected country based on the model's delivered CountryId value
$('#countriesList').val(500);
});
</script>
人口工作得很好,但在脚本添加的选项元素之一上调用 .val() 不会使其被选中,但作为一个例子,当我调用 .val( 时,静态定义的选项“500”工作正常)就可以了。
我对 jquery 相当陌生,但不是编程,因为我正在进入浏览器编程。任何提示都会有用。您还需要什么?
此脚本代码直接位于表 td 标记内,因此在呈现表单时填充并设置选择。
最佳答案
尝试手动完成。
var select = document.getElementBydId("countriesList");
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].value === "500") {
select.selectedIndex = i;
}
}
等等。问题是你使用的 AJAX 是异步的并且有回调
所以执行顺序是:
- 获取JSON
- 选择时设置值
- 添加选项以供选择。
因此,将 $("#countriesList").val(500)
添加到回调函数的末尾
关于javascript - jquery设置选中的选择选项;不适用于动态添加的选项,但适用于静态选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4830040/