我第二天试图解决这个问题。我有一个从AJAX调用动态创建的选择/选项列表。 AJAX调用填充选项(Jira项目),当用户从选项中选择项目时,我想触发一个事件,以便我可以捕获所选项目,然后再进行一次AJAX调用,将该特定项目的属性填充到另一个项目中。选择/选项下拉列表。
最初的AJAX调用看起来像这样(稍微修改了原始的jQuery $.get example),并且很好地填充了下拉列表(您需要登录Jira才能使其正常工作):
JS:
function getProjects(){
var jiraProject = $.get( "https://jira.atlassian.com/rest/api/2/project", function() {
alert( "success" );
})
.done(function() {
jiraProject = jiraProject.responseJSON;
var select = document.getElementById("jiraProjectsList");
for (i = 0; i < jiraProject.length; i++) {
var opt = document.createElement('option');
opt.value = jiraProject[i].name;
opt.innerHTML = jiraProject[i].name;
select.appendChild(opt);
}
$('#jiraProjectsList').hide().show();//refreshes the option list
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
// Perform other work here ...
// Set another completion function for the request above
jiraProject.always(function() {
alert( "second finished" );
});
}
HTML:
<label for="jiraProjectsList">JIRA Projects</label>
<select name="jiraProjectsList" id="jiraProjectsList" data-native-menu="false" class="filterable-select"></select>
我似乎无法弄清楚如何在用户选择选项时触发更改事件。
这是我尝试的各种事物的缩写选择:
$("#jiraProjectsList").change(function() {
alert("Inside jiraProjectList change function");
var selectedProject = $(this.val());
console.log(selectedProject);
getComponents(selectedProject.key);//next AJAX call
});
$("#jiraProjectsList").find(":selected").change(function(){
alert("hi mom!");
});
来自this SO question我试过了:
$('#jiraProjectsList').on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
});
来自this SO question,我尝试过:
$('#jiraProjectsList').find('option').click(function () {
var optionSelected = $(this);
var valueSelected = optionSelected.val();
var textSelected = optionSelected.text();
console.log(optionSelected);
console.log(valueSelected);
console.log(textSelected);
});
$('select').change(function () {
var optionSelected = $(this).find("option:selected");
var valueSelected = optionSelected.val();
var textSelected = optionSelected.text();
});
使用此功能,如果在程序流程中专门调用项目名称,我可以获取项目名称:
function getSelectedProjectName(){
var projectName = $("#jiraProjectsList").find(":selected").text();
console.log(projectName);
}
问题:
当用户做出选择时,如何在动态创建的选项/选择上触发更改事件?
答案:(来自SO帖子,这被标记为副本):
$(document).on('change', '#jiraProjectsList', function(){
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
console.log(optionSelected);
console.log(valueSelected);
});