function CascadeDropDowns(parentClass, childClass, action, callback) {
var DropDownId = $(parentClass + " option:selected").val();
$.ajax({
url: "/site/" + action,
data: { DropDownId: DropDownId },
dataType: "json",
type: "POST",
error: function () {
alert("An error occurred.");
},
success: function (data) {
var items = "";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
});
$(childClass).html(items);
$(childClass)[0].selectedIndex = 0;
callback();
}
});
}
$(document).ready(function () {
// Populates all child drop downs on load
var callback = function () {
CascadeDropDowns(".ConfigGroupDDL", ".ConfigNameDDL", "GetParameters");
};
CascadeDropDowns(".DeviceTypeDDL", ".ConfigGroupDDL", "GetGroups", callback);
// Populates all child drop downs parent change
$(".DeviceTypeDDL").change(function () {
var callback = function () {
CascadeDropDowns(".ConfigGroupDDL", ".ConfigNameDDL", "GetParameters");
};
CascadeDropDowns(".DeviceTypeDDL", ".ConfigGroupDDL", "GetGroups", callback);
});
$(".ConfigGroupDDL").change(function () {
CascadeDropDowns(".ConfigGroupDDL", ".ConfigNameDDL", "GetParameters");
});
});
这样运行正常并按正确的顺序级联下拉列表,但是firefox调试器显示错误,即抛出警报并询问Id是否可以调试。
任何建议都会很棒
答案 0 :(得分:51)
这是因为你并不总是将回调传递给该方法。
success: function (data) {
var items = "";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
});
$(childClass).html(items);
$(childClass)[0].selectedIndex = 0;
if(callback) callback(); //check before calling it.
}
答案 1 :(得分:31)
这是因为您并不总是向callback
函数提供CascadeDropDowns
。
E.g。
CascadeDropDowns(".ConfigGroupDDL", ".ConfigNameDDL", "GetParameters");
您应修改您的函数以将callback
参数视为optionnal参数:
if (callback) {
callback();
}
一个常见的简写是:
callback && callback();