gpt4 book ai didi

jquery - 处理填充选择选项的延迟

转载 作者:行者123 更新时间:2023-12-01 05:09:24 24 4
gpt4 key购买 nike

我的代码尝试重新填充选项并选择一个元素。问题是填充需要执行大量任务,然后重新填充 3 个选择框。我的方法控件返回,但当我尝试选择时,选项尚未填充。在较慢的系统/浏览器中有时会发生这种情况。 (特别是在 IE 上)有没有办法使用 jQuery 或其他东西来防止这种情况?当加载/或正在加载所有选项时,浏览器是否会触发任何事件。这似乎是因为浏览器有时需要时间来填充选项,但方法控件已返回。

function myMethod() {
populateOptions();
if(document.getElementById('Id').options[index].text==existId){
$("#Id").val(existId);
}
}

function populateOptions() {
//Make ajax call
// repopulates options
}

最佳答案

由于 AJAX 调用默认是异步的,因此您需要将赋值移动到填充 select 的代码之后运行。否则,值分配会在响应返回之前发生。

我假设填充 select 的任何代码都设置为在收到响应后运行。因此,将您的值选择放在该代码之后应该可以解决问题。

(换句话说,它将进入 populateOptions() 函数内部。)

除此之外,在看不到代码的情况下很难提供解决方案。

<小时/>

编辑:以下是一些示例,说明了其工作原理。其中任何一项都比在请求中设置 async: false 更好。

您可以将需要等待响应的代码放置在 success: 回调内部

function populateOptions() {
$.ajax({
url: "some/path",
success: function( resp ) {
// Place ANY code that needs to wait for the response in here.
// This way it will not run until the successful response is received.
}
});
}
<小时/>

或者您可以将需要等待响应的代码放置在另一个函数中,然后从 success: 回调中调用该函数。

function populateOptions() {
$.ajax({
url: "some/path",
success: function( resp ) {
// Call this function when the successful response is received.
successFunction( resp );
}
});
}
function successFunction( resp ) {

// Place ANY code that needs to wait for the response in here.

}
<小时/>

或者,如果 populateOptions() 应该以不同的方式重用,那么您需要不同的回调,您可以从另一个函数传入一个函数,该函数将在 success 中调用:回调。

function myMethod() {
// Send a function as an argument when you call populateOptions()
populateOptions( function(resp){alert(resp);} );

// Code that does NOT need to wait can still go here
}
function populateOptions( callback_fn ) { // Receive the function that was sent
$.ajax({
url: "some/path",
success: function( resp ) {
// Call the function that was sent
callback_fn( resp );
}
});
}
<小时/>

或者采用与上面相同的示例,您实际上可以使用传入的函数作为 success: 回调。

function myMethod() {
// Send a function as an argument when you call populateOptions()
populateOptions( function(resp){alert(resp);} );

// Code that does NOT need to wait can still go here
}
function populateOptions( callback_fn ) { // Receive the function that was sent
$.ajax({
url: "some/path",
success: callback_fn( resp ) // Now the function passed is the callback
});
}

关于jquery - 处理填充选择选项的延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3141062/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com