更改事件后自动更新下拉列表

我有一个下拉列表,当更改另一个下拉列表时,通过jquery ajax调用填充,在change()事件上,代码执行此操作:

//dropdowns switching $("#eventActivity").bind("change", (function() { $.ajax({ type:"POST", url:"" + "/" + $(this).val(), data: "activityID=" + $(this).val(), cache: false, dataType: "json", success:function(data) { //empty the ddl $(".locationDDL").children("select:first").children("option").remove(); //go through the json data returned and edit the drop down for( var i = 0 ; i < data.length ; i++) { $(".locationDDL").children("select:first").append("" + data[i].name + ""); } } }); })).change(); //force change to run once so it works on load for the first dropdown option 

现在这些下拉菜单出现在单击“编辑”按钮时弹出的对话框中。 我将数据传递到编辑对话框,以便我可以预先填充对话框中的字段。 除了将下拉列表设置为正确的值之外,一切正常。
我用来做这个的代码在这里:

 $("#eventActivity").val(event.activityID); $("#eventActivity").change(); //force the change handler to update the dropdowns $("#eventLocation").val(event.locationID); 

如您所见,我设置第一个下拉列表的值,触发更改事件,该事件应将新值加载到第二个下拉列表,然后设置第二个下拉列表的值。 问题是第三行代码(设置#eventLocation)不起作用,而是下拉列表保留选中它的默认值,即下拉列表中的第一个值。

任何建议都非常感谢!

您应该在ajax请求的成功回调中设置最后一个下拉列表的值。 如果最后一个值设置取决于ajax请求是否完成,那么您应该在回调中使用它。 在上次设置值时,您的请求可能尚未完成。