javascript 未执行 jQuery 自动完成渲染项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7205699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:17:25  来源:igfitidea点击:

jQuery Autocomplete render item is not executed

javascriptjqueryautocomplete

提问by jviriza

I have two textboxes (input type text) on the same HTML that use the same autocomplete. The first text box works fine, but the second text box do not render the results. It communicate with the server and I get the results, but the rendering function is not even called. The only difference between the inputs is that one is in a div that start hidden and I show kind like Dialog window by setting z-order high and masking the HTML.

我在同一个 HTML 上有两个使用相同自动完成功能的文本框(输入类型文本)。第一个文本框工作正常,但第二个文本框不呈现结果。它与服务器通信,我得到了结果,但甚至没有调用渲染函数。输入之间的唯一区别是一个在开始隐藏的 div 中,我通过将 z-order 设置为高并屏蔽 HTML 来显示类似于 Dialog 窗口的类型。

Here is the CSS for the div where the second input box is located.

这是第二个输入框所在的 div 的 CSS。

   .windowBooking  {
      position:absolute;
      width:450px;
     /* height:200px; */
      display:none;
      z-index:9999;
      padding:20px;
    }

The autocomplete function:

自动完成功能:

$(".makeClass").autocomplete({
    source: function (request, response) {
        $('#Code').val(); //clear code value
        $.ajax({
            url: "myUrl",
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            dataType: 'json', //What kind of Result is expected. (Ex json, xml, etc)
            data: "{'searchItem':'" + request.term + "'}",
            success: function (data) {
                var item = [];
                var len = data.d.length;
                for (var i = 0; i < len; i++) {
                    var obj = { name: data.d[i].MakeReport, code: data.d[i].MakeCode };
                    item.push(obj);
                }
                response(item);
            }
        })
    },
    focus: function (event, ui) {
        $(this).val(ui.item.name);
        return false;
    },
    select: function (event, ui) {
        $('#Code').val(ui.item.code);
        $('#Name').val(ui.item.name);
        $(this).val(ui.item.name);
        return false;
    },
    open: function () {
        $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
    },
    close: function () {
        $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
    },
    minLength: 2,
    delay: 250
}).data("autocomplete")._renderItem = function (ul, item) {
    var temp = item.name;
    return $("<li></li>")
                .data("item.autocomplete", item)
                .append("<a>" + item.name + "</a>")
                .appendTo(ul);
};

The input boxes use the same class to call the autocomplete.

输入框使用相同的类来调用自动完成。

  <input id="OtherMake" type="text" maxlength="30" size="20" class="makeClass"/> <!-- It works -->

  <div id="dialogPlus" class="windowBooking">
                                     :
    <input  type="text" id="MakeName"  class="makeClass" /> <!-- doesn't work.-->
                                     :
 </div>

Any ideas, why render on one input box and no in the other input box? Let me make clear, on the second input box the only thing not working is the renderItem function which for some reason it doesn't get executed. On the screen, you can see a lot of undefined but if you select any of the undefined values then the input box is filled with the correct value.

任何想法,为什么在一个输入框上渲染而在另一个输入框中不渲染?让我说清楚,在第二个输入框中,唯一不起作用的是 renderItem 函数,由于某种原因它没有被执行。在屏幕上,您可以看到很多未定义的值,但如果您选择任何未定义的值,则输入框将填充正确的值。

回答by user1359977

I had a similar issue applying _renderItem() on a class selector but solved it with

我在类选择器上应用 _renderItem() 时遇到了类似的问题,但解决了

$.each($( ".makeClass" ), function(index, item) {
        $(item).data("autocomplete")._renderItem = function (ul, item) {
        return $("<li></li>")
                .data("item.autocomplete", item)
                .append("<a>" + item.value + " - " + item.label + "</a>")
                .appendTo(ul);
        };
          });

回答by jviriza

I still don't know what is causing the problem, but I was able to make it work by using the ID instead of using a class to access autocomplete. My guess is that an appended render function cannot be shared between two input boxes? I don't know, if somebody knows the answer and could share with us, it would be great.

我仍然不知道是什么导致了问题,但我能够通过使用 ID 而不是使用类来访问自动完成来使其工作。我的猜测是不能在两个输入框之间共享附加的渲染功能?我不知道,如果有人知道答案并可以与我们分享,那就太好了。

Anyway, if somebody happen to have the same weird problem as me and it is stuck with the problem, here is how I solved it. As, I didn't want to repeat the same code twice, I moved all the autocomplete logic to a var and the render function to another var and used the input box ID to assign autocomplete.

无论如何,如果有人碰巧遇到和我一样奇怪的问题并且被这个问题所困扰,这就是我解决它的方法。因为,我不想重复相同的代码两次,我将所有自动完成逻辑移到一个 var 并将渲染函数移到另一个 var 并使用输入框 ID 分配自动完成。

  var makeAutocomplete = {
        source: function (request, response) {
            $('#Code').val(); //clear code value
            $.ajax({
                url: myUrl,
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                dataType: 'json', //What kind of Result is expected. (Ex json, xml, etc)
                data: "{'searchItem':'" + request.term + "'}",
                success: function (data) {
                    var item = [];
                    var len = data.d.length;
                    for (var i = 0; i < len; i++) {
                        var obj = { name: data.d[i].MakeReport, code: data.d[i].MakeCode };
                        item.push(obj);
                    }
                    response(item);
                }
            })
        },
        focus: function (event, ui) {
            $(this).val(ui.item.name);
            return false;
        },
        select: function (event, ui) {
            $('#Code').val(ui.item.code);
            $('#Name').val(ui.item.name);
            $(this).val(ui.item.name);
            return false;
        },
        open: function () {
            $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
        },
        close: function () {
            $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
        },
        minLength: 2,
        delay: 250
    };

    var renderList = function (ul, item) {
        return $("<li></li>")
                .data("item.autocomplete", item)
                .append("<a>" + item.name + "</a>")
                .appendTo(ul);
    };

    $("#OtherMake").autocomplete(makeAutocomplete).data("autocomplete")._renderItem = renderList;
    $("#MakeName").autocomplete(makeAutocomplete).data("autocomplete")._renderItem = renderList;

回答by expellee

I have this bug too. This is strange that with id as selector _renderItem works correct. I found a quick hack for this issue:

我也有这个bug 这很奇怪,使用 id 作为选择器 _renderItem 工作正常。我找到了解决这个问题的快速方法:

$.ui.autocomplete.prototype._renderItem = function (ul, item) {}

回答by Cyril N.

For me, what fixed it was using the appendTooption from the jQuery UI AutoComplete.

对我来说,修复它的是使用jQuery UI AutoComplete 中appendTo选项。

My problem was that this input field was inside a modal that wasn't shown at first. Affecting it to the input's parent fixed the problem!

我的问题是这个输入字段在一个最初没有显示的模式中。将其影响到输入的父级解决了问题!