如何为2个组合框定义不同的来源?

时间:2011-11-05 12:00:58

标签: jquery jquery-ui

我使用来自jquery examples的组合框代码。 这是modified使用远程源。

现在我需要将second combobox添加到另一个远程来源(国家而不是城市)。当然,我可以使用给定的不同来源复制粘贴$.widget("ui.combobox", {,但有没有办法简化代码?

UPD。看起来我应该修改以下代码:

  $.widget( "ui.combobox", {
    _create: function() {
      var self = this,
        select = this.element.hide(),
        selected = select.children( ":selected" ),
        value = selected.val() ? selected.text() : "";
      var input = this.input = $( "<input>" )
        .insertAfter( select )
        .val( value )
        .autocomplete({
          delay: 0,
          minLength: 0,

          source: function (request, response) {
              // if id of element is equal to something, then use one url, else
              // use another url
              $.ajax({
                  url: "search/city", type: "GET", dataType: "json",
                  data: { term: request.term },
                  success: function (data) {
                      response($.map(data, function (item) {
                          return {
                              value: item.value,
                              id: item.id
                          }
                      }))
                  }
              })
          },

但我不知道如何在source函数中获取元素id。

1 个答案:

答案 0 :(得分:4)

编辑:让我的帖子更清晰。您只需使用self.options来获取所有声明的选项。 this.options无法在$.ajax({...})内使用,因为该上下文中的this将返回匿名函数。

如果更改了行

 $.ajax({
     url: "http://ws.geonames.org/searchJSON",

$.ajax({
     url: self.options.source,

,然后ajax调用将使用您在“构造函数”中提供的任何源URL。然后你可以简单地做:

$("#cbCountry").combobox({
    source: someOtherUrl,
   ...
});

用于不同的组合框。请参阅http://jsfiddle.net/k2J5v/1/