jquery设置选择的选项;不适用于动态添加选项工作,但确实为静态的
问题描述:
这里是我有一个正确填充选择列表:jquery设置选择的选项;不适用于动态添加选项工作,但确实为静态的
<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()由脚本添加的元素不会使其被选中,但作为示例,静态定义的选项“500”在我调用.val()时正常工作。
我对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和异步是,有一个回调
所以执行顺序是:在选择
- 的getJSON
- SETVAL选择。
所以添加$("#countriesList").val(500)
到你的回调函数
答
结束时,如果你想在同一地点你的例子.val(500)
是选择它,你永远不会有一个工作的结果。 AJAX调用是异步进行的,并在.val(500)
已被执行后填充信息。
在ajax调用的返回函数中移动你的选择,它应该工作正常。
谢谢。将.val()调用放在正确的位置后,完美地工作。那不是点击。谢谢! – slimflem 2011-01-28 15:56:05
你救了我的命!非常棒! – rubdottocom 2011-02-11 11:20:31