【问题标题】:jQuery Autocomplete update source with object - formatting the array带有对象的jQuery自动完成更新源 - 格式化数组
【发布时间】:2012-10-31 01:46:29
【问题描述】:

我正在尝试动态更新 jQuery UI 源。我可以用这样的数组很好地做到这一点:

  var arrProducts = ['cheese' , 'bread' ,  'milk'];

但需要使用对象来完成。在切换到使用 AJAX 之前,这在第一页加载时运行良好,将一组对象从 PHP 传递到 Twig:

 var arrProducts = [
                      {% for product in allproducts %}
                          {
                              title:  "{{ product.title }}",
                              url:  "{{ product.url }}",                                 
                              label: "{{ product.label }}"                              
                          },
                      {% endfor %}
              ];

那么,如何在 javascript 中复制这种格式?我试过这个:

                           var arrProducts = [];

                            $.each(data.products, function(index, product)
                            {
                                   prod['title'] = product.title;
                                   prod['url'] = product.url;
                                   prod['label'] = product.label;

                                   arrProducts.push(prod);
                            });                          

                           $('.searchBox' ).autocomplete( "option", "source", arrProducts );

但这会产生嵌套对象,然后自动完成似乎无法正确读取。

【问题讨论】:

    标签: javascript jquery user-interface autocomplete jquery-autocomplete


    【解决方案1】:

    jQueryUI 文档指出source 数组应包含具有labelvalue 属性的对象:http://api.jqueryui.com/autocomplete/#option-source;你的对象没有value 属性。

    我不清楚为什么这以前会起作用,但这里有一个对我有用的修改:我将您的 prod['title'] 更改为 prod['value'],并将 prod 预先声明为局部变量,因此它不会被自动实例化作为一个全球性的。

    另外请注意,我必须更改“选项”调用以使用匿名对象;出于某种原因,尝试调用 $('.searchBox').autocomplete("options", "source", arrProducts); 导致我的测试小提琴出现错误。

    HTML

    ​<input type="text" class="searchBox"/>​​​​​​​​​​​​​​​​​​​​​​​​​​​
    

    JavaScript

    var products = [
        {
          title: 'cheese',
          url: 'http://www.example.com',
          label: 'Swiss Cheese'
        },
        {
          title: 'bread',
          url: 'http://www.example.com',
          label: 'Wheat Bread'
        },
        {
          title: 'milk',
          url: 'http://www.example.com',
          label: '1% Milk'},
    ];
    
    var arrProducts = [];
    
    $.each(products, function(index, product) {
        var prod = {};
        prod['value'] = product.title;
        prod['url'] = product.url;
        prod['label'] = product.label;
    
        arrProducts.push(prod);
    });
    
    $('.searchBox').autocomplete({ source: arrProducts });
    

    【讨论】:

    • 添加值是问题所在。然后我也添加了一个标题属性。
    猜你喜欢
    • 2015-08-26
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 2023-03-22
    • 2019-06-11
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多