【问题标题】:Bootstrap Typeahead click eventBootstrap Typeahead 点击事件
【发布时间】:2013-03-31 23:06:44
【问题描述】:

我正在使用 bootstrap-typeahead.js v2.0.0 进行自动完成搜索。我有一个点击事件来查看结果,但它只能工作 10 次中的 1 次,在另一种情况下我收到错误:“Uncaught SyntaxError: Unexpected token u”。

我环顾四周,发现了这个:https://github.com/twitter/bootstrap/issues/4018,我尝试了那里的解决方案,但似乎没有任何效果。当我使用回车键时它工作得很好,所以它必须与点击事件有关。其他人有同样的问题吗? 代码:

$('#search').typeahead({

        source: function (typeahead, query) {
                $.ajax({
                    type: "GET",
                    url: "search/" + query,
                    success: function (data) {
                        searchResult = data;
                        return typeahead.process(data);
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        console.log(thrownError);
                    }
                }); 
        }
        },
        onselect: function (obj) {
            window.location.href = "view/" + obj.id;
        },
        items: 8,
        minLength: 1,
        highlighter: function (item) {
        var artist = _.find(searchResult, function (a) {
            return item === a.value;
        });
        return ('<li>' + artist.value + ' (' + artist.dbirth + '-' + artist.ddeath + ')<li>');
        }
    });

【问题讨论】:

    标签: javascript jquery bootstrap-typeahead


    【解决方案1】:

    好的,我自己解决了。这是你必须做的:

    打开bootstrap-typeahead.js,在第203行找到listen方法,修改如下:

        listen: function () {
        this.$element
        .on('blur',     $.proxy(this.blur, this))
        .on('keypress', $.proxy(this.keypress, this))
        .on('keyup',    $.proxy(this.keyup, this))
    
        // if ($.browser.webkit || $.browser.msie) {
        this.$element.on('keydown', $.proxy(this.keypress, this))
        // }
    
        this.$menu
        .on('click', $.proxy(this.click, this))
        .on('mouseenter', 'li', $.proxy(this.mouseenter, this))
        .on('mouseleave', 'li', $.proxy(this.mouseleave, this))
        }
    

    这里唯一的区别是我在“mouseleave”上添加了一个监听器。

    转到第 278 行的 mouseenter 方法并将其更改为:

    mouseenter: function (e) {
          $(e.currentTarget).addClass('active')
        }
    

    然后添加一个名为“mouseleave”的新方法并添加以下代码:

    mouseleave: function () {
          this.$menu.find('.active').removeClass('active')
    }
    

    希望这对遇到类似问题的人有所帮助。

    【讨论】:

      【解决方案2】:

      这是一个更简单的解决方案。 “Blur”事件在点击事件之前绑定。只需为模糊添加延迟,这将解决问题。

      <input type="text" placeholder="Enter a Name" onblur="hidesuggest();" id="suggestbox">
      <script>
      function hidesuggest(){
          setTimeout("$('#suggestbox').toggle();",200);
      }
      </script>
      

      额外的 200 毫秒为“单击”绑定在鼠标单击时执行提供了足够的时间。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-26
        • 2017-10-09
        • 2012-03-21
        相关资源
        最近更新 更多