【问题标题】:How to add additional <li> in jQuery autocomplete?如何在 jQuery 自动完成中添加额外的 <li>?
【发布时间】:2018-04-11 12:23:47
【问题描述】:

我想构建一个自动完成的 jQuery 自动完成功能。 我想添加一个额外的&lt;li&gt; 在列表的末尾。 所以我用了这个:

$( function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  } );
  
  
  jQuery.ui.autocomplete.prototype._renderMenu = function( ul, items 			) {

        var that = this;
        $.each( items, function( index, item ) {
            that._renderItemData( ul, item );
        });
       $( ul ).append("<li class='selectall'>show all</li>");
       
       $( ".selectall" ).on( "click", function() {
   				console.log("select!");
          $( ".label" ).css("color", "red");
        } );
       
    };
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
  <label class="label" for="tags">Tags: </label>
  <input id="tags">
</div>

当我将鼠标悬停在额外的&lt;li&gt; 上时,除了控制台中出现的错误消息之外,这一切正常。 也许那是因为除了我的附加&lt;li&gt; 之外,每个&lt;li&gt; 都有一个值和一个键。 但我不知道如何避免该错误消息。

我也试过这个:Add a additional <li> tag to the end of rails3-jquery-autocomplete plugin

但还是一样。

【问题讨论】:

  • 如果您从下拉列表中检查您的&lt;li&gt;,您会看到 li 标签也包含一个&lt;div&gt; 元素,请尝试添加该 div 元素。

标签: javascript jquery jquery-ui autocomplete


【解决方案1】:

看来_renderMenu是在_renderItem之前执行的,所以 您可以在_renderMenu 中添加新项目并在_renderItem 中呈现它。

$.widget( "custom.autocomplete", $.ui.autocomplete, {
    _renderMenu : function( ul, items            ) {

        var that = this;
        items.push({label:"show all", value:"", isShowAll:true})
        $.each( items, function( index, item ) {
            that._renderItemData( ul, item );
        });

    },
    _renderItem: function( ul, item ) {
        var li = $( "<li>" )
            .attr( "data-value", item.value )
            .append( item.label )
            .appendTo( ul );

        if(item.isShowAll===true){
            li.on( "click", function() {
                console.log("ShowAll selected");

            });
        }
        return li;
    }    
});

注意:我使用的是$.widget而不是原型,但我猜结果应该是一样的。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-28
  • 1970-01-01
  • 2014-02-04
  • 2015-08-29
  • 2011-05-28
相关资源
最近更新 更多