jQuery Autocomplete .data(“autocomplete”) is undefined

前端 未结 6 1448
盖世英雄少女心
盖世英雄少女心 2021-02-03 20:58

When I try to implement auto-complete using the code below I get an error stating:

.data(\"autocomplete\") is undefined

How ever if I remove th

6条回答
  •  被撕碎了的回忆
    2021-02-03 21:22

    Actually in your success function you are calling response and returning an object like

    return {
               label: item.name,
               image: item.picture,
               json: item,
           }
    

    but in the following line

    return $("
  • ").data("item.autocomplete", item).append("no photo" + item.label + " Number of Likes: " + item.likes).appendTo(ul);

    you are using item.likes that is not available in your returned object, so it's the problem. I think you can use it like

    success:function(data) {
        var result = $.map(data, function (item){
        return {
                label: item.name,
                image: item.picture,
                item.likes 
            };
        });
        response(result);
    }
    

    Also keep the item.label inside the (it may not a cause for the error), like

    return $("
  • ").data("item.autocomplete", item).append("no photo"+item.label+"").appendTo(ul);

    and make sure in the following line

    $.map(data.data, function (item) // notice data.data
    

    whether it should be data.data or only data. You can also remove the json: item from the object because you didn't use it anywhere, as far as I'm concerned.

    Update: Change following line

    .data("autocomplete")._renderItem = function (ul, item) {...};
    

    to

    .data("autocomplete")?._renderItem = function (ul, item) {...}; // notice the ? mark
    

    or

    if(typeof $('#Your_Input_Id').val()!="undefined")
    {
        $('#Your_Input_Id').autocomplete({....});
    }
    

    or

    var mydata=$('#Your_Input_Id').autocomplete(...).data('autocomplete');
    if(mydata)
        mydata._renderItem = function (ul, item) {...};
    

提交回复
热议问题