问题描述
小提琴应该用来帮助说明我正在尝试做的事情和正在发生的事情.子选择项应填充第二个选项值.
The fiddle should be used to help illustrate what I'm trying to do and what's happening. The sub-selects should be populated with the second option value.
不确定最好的提问方式.我正在创建一个测试脚本以自动填充表单上的输入.
Not sure the best way to ask. I'm creating a testing script to autofill inputs on a form.
它包括一系列下拉select
框,这些框填充onChange事件中的其他select
选项.尝试自动填充表单时,子选择没有任何选项.
It includes a series of drop-down select
boxes, which populate other select
options in an onChange event. When trying to auto-populate the form, the sub-selects don't have any options.
console.clear();
// non-select inputs
$(':input:not([type="hidden"],[type="button"])').each(function(){
$(this).val($(this).attr('name')) // test value is simple input's name
});
// select inputs
var count=0, cutoff=7500;
$('select').each(function(){
var t = $(this);
var c = t.children('option');
while( c.length <= 1 && count < cutoff){
count++;
c = $(this).children('option'); // tried not using the cache'd variable
if (!(count % 10))
console.log(count, c.length, "No Options"); // debugging -- never exists early
setTimeout(function(){},0); // not really doing anything
}
t.val( c.eq(1).val() ); // set value to second option value
t.trigger('change'); // calls the onChange even if it doesnt exist
});
// verify it does have data
console.log($('#sub-select').children('option').length); // does have options
在change事件中有一个AJAX调用.我可以修改回调,但这只是一个简单的测试脚本,是从控制台运行的.有什么想法吗?
There's an AJAX call in the change event. I could modify the callback, but this is just a simple set script for testing, that is run from console. Any ideas?
推荐答案
您的问题是您正在函数中启动AJAX请求,并期望响应在函数结束之前到达.只要您使用异步请求,就永远不会发生这种情况.您必须先退出函数,然后才能运行处理响应的代码. Javascript是单线程的,因此只要您的函数正在运行,其他任何代码都无法运行.
Your problem is that you are starting an AJAX request in the function, and expect that the response arrives before the function ends. As long as you are using an asynchronous request, this will never happen. You have to exit your function before the code that handles the response can run. Javascript is single threaded, so as long as your function is running, no other code can run.
该问题的解决方案是将使用数据的代码放入响应到达后调用的成功回调函数中.尽管通常会在调用AJAX的函数中编写该函数,但它是一个单独的函数,稍后会运行.
The solution to the problem is to put the code that uses the data in the success callback function that is called after the response has arrived. Eventhough you usually write that function inside the function that makes the AJAX call, it's a separate function that will run later.
如果您确实需要与AJAX调用相同功能的数据,则需要发出一个同步请求.不过,这是用户体验的杀手,,因为整个浏览器在等待响应时都会冻结.
If you really need the data in the same function as the AJAX call, you would need to make a synchronous request. This is a killer for the user experience, though, as the entire browser freezes while it is waiting for the response.
这篇关于JavaScript:在另一个函数调用完成后,继续执行该函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!