输入预先点击事件

Bootstrap Typeahead click event

本文关键字:事件 输入      更新时间:2023-09-26

我使用bootstrap-typeahead.js v2.0.0进行自动完成搜索。我有一个点击事件来查看结果,但它只像10次中的1次一样工作,在另一种情况下,我得到一个错误:"未捕获的SyntaxError:意外的令牌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>');
        }
    });

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

打开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')
}

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

<input type="text" placeholder="Enter a Name" onblur="hidesuggest();" id="suggestbox">
<script>
function hidesuggest(){
    setTimeout("$('#suggestbox').toggle();",200);
}
</script>
额外的200毫秒为"click"绑定在鼠标单击时执行提供了足够的时间。