33
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 是否可以调试。

任何建议都会很棒

4

2 回答 2

64

这是因为您并不总是将回调传递给该方法。

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. 
}
于 2013-04-09T14:57:56.907 回答
37

这是因为您并不总是callback为该CascadeDropDowns功能提供 a 。

例如

CascadeDropDowns(".ConfigGroupDDL", ".ConfigNameDDL", "GetParameters");

您应该修改您的函数以将callback参数视为可选参数:

if (callback) {
    callback();
}

一个常见的简写是:

callback && callback();
于 2013-04-09T14:58:29.537 回答