在 jQuery 中加载下拉值后设置下拉选择值
Set dropdown selected value after loading dropdown values in jQuery
我正在尝试在下拉列表成功加载后在下拉列表中设置选定值。
我在设置选定值后按 ajax 或 jQuery 加载下拉列表值,但有时它工作正常,有时它不会设置选定值,因为加载下拉列表延迟。我也尝试过 setTimeout,如下所示,但它无法正常工作:
if($("#ddlToUnit").length>0)
{
setTimeout($("#ddlToUnit option[value='"+data.Records.GxMovement.ToUnit_v+"']").attr("selected","selected"),1000);
}
else
{
$("#ddlToUnit option[value='"+data.Records.GxMovement.ToUnit_v+"']").attr("selected","selected");
}
我想在加载下拉列表后设置所选值...
谢谢
您可以使用 setInterval
来继续检查元素是否已填充。第一个 setTimeout
函数只是模拟用 3 秒向列表中添加一个选项。
setTimeout(function() {
var newOption = document.createElement('option');
newOption.innerHTML = 'Option Text';
document.getElementById('list').appendChild(newOption);
}, 3000);
// Do something only after list is populated
var interval = setInterval(function() {
if (document.querySelectorAll('#list option').length > 0) {
console.log('List is definitely populated!');
clearInterval(interval);
}
}, 200);
<select id="list">
</select>
我正在尝试在下拉列表成功加载后在下拉列表中设置选定值。
我在设置选定值后按 ajax 或 jQuery 加载下拉列表值,但有时它工作正常,有时它不会设置选定值,因为加载下拉列表延迟。我也尝试过 setTimeout,如下所示,但它无法正常工作:
if($("#ddlToUnit").length>0)
{
setTimeout($("#ddlToUnit option[value='"+data.Records.GxMovement.ToUnit_v+"']").attr("selected","selected"),1000);
}
else
{
$("#ddlToUnit option[value='"+data.Records.GxMovement.ToUnit_v+"']").attr("selected","selected");
}
我想在加载下拉列表后设置所选值...
谢谢
您可以使用 setInterval
来继续检查元素是否已填充。第一个 setTimeout
函数只是模拟用 3 秒向列表中添加一个选项。
setTimeout(function() {
var newOption = document.createElement('option');
newOption.innerHTML = 'Option Text';
document.getElementById('list').appendChild(newOption);
}, 3000);
// Do something only after list is populated
var interval = setInterval(function() {
if (document.querySelectorAll('#list option').length > 0) {
console.log('List is definitely populated!');
clearInterval(interval);
}
}, 200);
<select id="list">
</select>