私は、DOMの準備ができたらデータベースからプロジェクト名を取得するアプリケーションを持っています。各プロジェクトは、の<select><option>
に追加されています。リストにデータが入力されると、ユーザーはプロジェクトタイトルを選択できます。プロジェクトタイトルは、そのプロジェクトに固有のデータベースから残りの情報を要求します。jQuery .change()イベントは一度だけ発生します
これを実現するには、$.change()
jQueryメソッドを使用しています。残念ながら、イベントは、<select>
要素が作成されてDOMに追加されたときに1回だけ発生します。リストから別のプロジェクトを選択してもイベントは発生しないため、$.post()
呼び出しは実行されません。
$(document).on('change', 'select', retrieveProject);
を処理する必要が
$(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