我的文档加载并使用 URL 中的变量(GET 变量)并更改 <select>
将元素的选定值更改为 URL 中指定的值
这很容易,因为 <select>
文档加载时已经填充,我只需要更改选定的值。
第二个<select>
通过ajax填充第一个数据(嵌套类别的东西),我可以在“文档加载”上填充它,但我不知道如何更改其选定的值。
我知道这可能必须通过委托(delegate)事件来完成,但我只通过点击事件等来完成。
我尝试过的事情:
取自 jQuery 文档网站:
$( "#select-with-ajax-vals" ).on( "change", function( event ) {
console.log("hello"); //works
$('#select-with-ajax-vals').val(value_from_the_url); //doesn't work but the same exact code pasted in the console works.
});
$(document).ready(function(){
//populate the lists
....
//lists populated etc
$('#select-with-ajax-vals').trigger("change");
});
代码已简化,但您明白了。
最佳答案
正如您所提到的,数据是通过 ajax 填充的。我认为发生的情况是,当您在文档加载时触发 #select-with-ajax-vals 时。数据尚未填充。
您可能想尝试以下代码:
$( document ).ajaxStop(function() {
$( "#select-with-ajax-vals" ).on( "change", function( event ) {
console.log("hello"); //works
$('#select-with-ajax-vals').val(value_from_the_url); //doesn't work but the same exact code pasted in the console works.
});
$('#select-with-ajax-vals').trigger("change");
});
关于javascript - 更改文档准备好时由 ajax 填充的选择的选定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31805496/