我希望这段代码可以帮助人们尝试做同样的事情,但是,我有一个小错误需要帮助。
我的下拉菜单中有一个按钮,可打开一个模式以向数据库中添加新项(然后进入下拉菜单)。我的代码成功添加了项目,但是“添加”按钮消失了。
添加之前:
添加后:
HTML:
<!--Journal-->
<li>
<div class="pt-3 pb-0 px-4" id="journal">
<select class="dropdown-select mt-0 journals_dropdown" id="journals_dropdown" required>
<option value="" disabled selected>Select</option>
</select>
<button class="btn-save btn btn-primary btn-sm add_journal_button" data-toggle="modal" data-target="#add_journal_modal">Add</button>
</div>
</li>
<!--/Journal-->
JS:
//===== Fill Journals Dropdown =====
function fill_journals() {
$('#journals_dropdown').empty();
//add items to dropdown
for (var i=0; i<journals.length; i++) {
$('#journals_dropdown').append($('<option></option>').val(journals[i]._id).html(journals[i].journal_name));
}
//$('#journal').append('<button class="btn-save btn btn-primary btn-sm add_journal_button" data-toggle="modal" data-target="#add_journal_modal">Add</button>');
//select latest item from dropdown
if(localStorage.getItem('latest_journal').length > 15) {
$("#journals_dropdown").val(localStorage.getItem('latest_journal')).attr("selected","selected");
}
}
错误是由JS中的这段代码引起的(如果我注释掉,按钮不会消失):
//add items to dropdown
for (var i=0; i<journals.length; i++) {
$('#journals_dropdown').append($('<option></option>').val(journals[i]._id).html(journals[i].journal_name));
}
PS。如果刷新页面,则fill_journals()会像超级按钮一样工作。这样添加新日记帐表单后,我会尝试调用它;
$.ajax({
url: '/add_journal',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify(data),
success: function (response) {
$('#add_journal_modal').modal('toggle');
localStorage.setItem("latest_journal", response);
initialize(); //fill_journals() is part of this
// location.reload();
}
});