我已经使用 jQuery 编写了一些 javascript,用 div 和 ul 替换任何选择列表,这样它会给我更多的样式控制,并使下拉列表在浏览器中看起来相同。下面的代码对我来说 99% 有效,但我有一个问题。在代码的底部,我不得不使用 .delay() 来告诉代码等待上面的 .each() 循环完成它正在做的事情。这样做的问题是,在替换发生之前至少有一秒钟,旧的选择框会闪现。我还可以预见另一个问题是,如果 each() 循环完成需要超过一秒怎么办...
如何让底部的代码仅在每个循环运行并完成后运行。我也欢迎对其余代码进行任何优化。
编辑:一些 HTML 已从代码中删除,因此我将其粘贴:http://pastebin.com/4HFLjHE1
// Check when ready
$(function() {
// Find dropdowns
$("select.dropdownreplace").each(function() {replaceDropDown(this);});
// If document clicked anywhere hide drop downs
$(document).click(function(event){
$("div.dropdownreplace ul").hide();
});
});
function replaceDropDown(that) {
// Create HTML for new drop down
// hidden field
var hiddeninput = $('');
// div
var dropdowndiv = $(''+$(":selected", that).text()+'<ul></ul>');
// loop through values and make li's
$("option", that).each(function() {
$("ul", dropdowndiv).append('<li>'+$(this).val()+''+$(this).text()+'</li>');
// set click handler for this drop down
$(dropdowndiv).click(function() {
$("ul", this).show();
return false;
});
// set click handler for link items
$("a", dropdowndiv).click(function() {
// Get name of hidden input
var nameofdropdown = $(this).parent().parent().parent().attr('id');
var nameofinput = nameofdropdown.replace("dropdownreplacement_", "");
// set hidden input value to whats been clicked
$("[name='"+nameofinput+"']").val($(this).parent().find("span").text());
// set div
$("div#"+nameofdropdown+" > span").text($(this).text());
$("div#"+nameofdropdown+" ul").hide();
return false;
});
});
// Remove drop down then add in replacement html
$(that).delay(1000).after(hiddeninput);
$(that).delay(1100).after(dropdowndiv);
$(that).delay(1200).remove();
}
谢谢
斯科特
最佳答案
在您的函数内,将 jquery 传递给您的索引与您拥有的项目总数进行比较。
我不知道你的html,但我相信你能做到。
更改您的函数,使其接收 jquery 发送的索引参数。
$("option", that).each(function(index) {
然后,在那个函数的最后比较长度和索引,如果它们相同,那么你就完成了
if ( $('option', that).length == (index +1 ) ) {
$(that).after(hiddeninput);
$(that).after(dropdowndiv);
$(that).remove();
}
根据我的测试,这应该是您所需要的。不知道是否有更“标准”的方法来做到这一点。
希望对你有帮助
关于javascript - jQuery 等待上面的代码执行完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3683514/