我有一个列出主题的下拉菜单。我通过AJAX调用加载这些主题。对象加载正确,它们加载速度不足以填充选择菜单,直到菜单打开后。这导致用户需要打开菜单,关闭菜单,然后再次打开它。
如何在下拉菜单中打开延迟,让响应有足够的时间填充下拉菜单?感谢您的帮助。
代码:
下拉菜单
<div id="subjectForm" class="form-row">
<label>1) Subject Selection:</label>
<select name="subject" id="subjectSelect" class="input-medium">
<option value="0">All</option>
</select>
</div>
AJAX致电
document.getElementById("subjectForm").addEventListener("click", function( event ) {
var selectCount = $('#subjectSelect option').size();
if(selectCount == 1) {
$.ajax({
url: '/v2/subjects?',
method: 'GET',
data: {'core': number},
success: function (data) {
// Populates the $subjectSelect filter with subjects
// For each grade brought back from response, add it to the grade filter
$.each(data, function(i, subject){
$('#subjectSelect')
.append($('<option></option>')
.attr("value", subject.id)
.text(subject.title));
});// each
}// success
});// ajax
}// end if
}, false);// #subjectForm clicked
答案 0 :(得分:0)
几秒钟后渲染选项
success: function (data) {
// Populates the $subjectSelect filter with subjects
// For each grade brought back from response, add it to the grade filter
var myoptions = "";
$.each(data, function(i, subject){
myoptions += "<option value='"+subject.id+"'>"+subject.title+"</option>";
});
$('#subjectSelect').html(myoptions);
}
希望它能解决问题。
答案 1 :(得分:0)
由于number
值是默认的,我会在文档就绪时更改负载,而不是等到点击事件。
$(document).ready(function () {
var loadSubjectSelect = function(){
var selectCount = $('#subjectSelect option').size();
if(selectCount == 1) {
$.ajax({
url: '/v2/subjects?',
method: 'GET',
data: {'core': number},
success: function (data) {
// Populates the $subjectSelect filter with subjects
// For each grade brought back from response, add it to the grade filter
$.each(data, function(i, subject){
$('#subjectSelect')
.append($('<option></option>')
.attr("value", subject.id)
.text(subject.title));
});
}
});
}
};
loadSubjectSelect();
})();
然后,当您添加其他菜单时,可以在其点击事件上调用loadSubjectSelect()
。