我有一个应用程序,当DOM准备好时,从数据库检索项目名称。每个项目都添加到html
为了实现这一点,我使用了
<form>
中的<select><option>
中。一旦列表被填充,用户可以选择项目标题,这将请求与该项目相关的其余信息。为了实现这一点,我使用了
$.change()
jQuery方法。不幸的是,当<select>
元素被创建并添加到DOM中时,事件只会触发一次。从列表中选择另一个项目不会触发事件,因此也不会触发$.post()
调用。$(function(){
getProjects();
var firstLoad = true;
$("select").change(retrieveProject); // Removed parenthesis based on answers
// On page load, get project names from the database and add them to a Select form element
function getProjects() {
var selectionList;
$.getJSON("php/getProjects.php", function (data) {
selectionList = "<form><select>";
for (var i = 0; i < data.length; i++) {
selectionList += "<option name='prjTitle'>" + data[i].ProjectTitle + "</option>";
}
selectionList += "</select></form>";
}).complete(function() {
$('#project-selection-menu').append(selectionList).removeClass('hidden');
firstLoad = false;
});
}
function retrieveProject() {
if ( firstLoad == true ){
alert(firstLoad); // This alert fires
return false;
} else {
alert(firstLoad); // This alert doesn't fire
$.post("php/getProjects.php", function (data) { // This should have been "php/retrieveProject.php"!
// Do stuff with the returned data
}).complete(function() {
console.log("Success.");
});
}
}
)};
getProjects();
调用以减少显示的代码量,但这显然引起了更多混淆。 - Roy