【问题标题】:JQuery: Twitter Typeahead function for no matchJQuery:Twitter Typeahead 功能不匹配
【发布时间】:2013-08-03 18:44:08
【问题描述】:

我正在使用 typeahead.js 将产品 ID 分配给隐藏的 html 表单字段。这在匹配时非常有用:

$('.products_tt .typeahead').typeahead
    name: 'products_tt',
    prefetch: 
        url: '/products.json',
        ttl: 60 * 5e3
    template: '<p><strong>{{value}}</strong> – {{year}}</p>',
    engine: Hogan

$('.products_tt .typeahead').on "typeahead:selected typeahead:autocompleted", (e,datum) ->
    $('#disk_file_product_id').val(datum.id)

当输入字段为空白时,我清除隐藏字段:

$('.products_tt .typeahead').blur ->
    if $(this).val().length == 0
        $('#disk_file_product_id').val("")

但是当在输入字段中输入文本但没有匹配时,我还需要清除隐藏字段。

我的 Java/Coffeescript 技能很弱,所以不知道该怎么做?!?

【问题讨论】:

    标签: javascript jquery ruby-on-rails coffeescript typeahead.js


    【解决方案1】:

    以下其中一项应该有效:

    1) 首先挂钩输入字段的change 事件,然后清除#disk_file_product_id 那里。如果有选择,您的 typeahead 事件稍后将再次设置。这也节省了您的 blur 回调。

    $('.products_tt .typeahead').change ->
        $('#disk_file_product_id').val("")
    

    2) 在openedclosed 事件中清除#disk_file_product_id,而不是在字段的change 事件中。我不喜欢这个。

    $('.products_tt .typeahead').on "typeahead:opened typeahead:closed" ->
        $('#disk_file_product_id').val("")
    

    【讨论】:

    • 谢谢,#1 似乎可以解决问题!很好奇,我怎么能确定.change 事件总是在.on 事件之前触发?
    • 你不能,我想。代码的行为就是这样,如果它改变了,我会感到非常惊讶。如果是这样,事件的顺序将被“选择”然后“更改”。至少可以说很奇怪。
    【解决方案2】:

    我知道这已经几个月了,但你可以这样做:

    使用 jQuery 查看每个 keyup 事件的 DOM 中有多少“.tt-suggestions”。如果没有,请清除隐藏字段。

    $('.products_tt .typeahead').typeahead({
        name: 'products_tt',
        prefetch: url: '/products.json',
        ttl: 60 * 5e3
        template: '<p><strong>{{value}}</strong> – {{year}}</p>',
        engine: Hogan
    }).on("typeahead:selected typeahead:autocompleted", function (e, datum) {
        $('#disk_file_product_id').val(datum.id);
    }).on('keyup', function () {
        if($('.tt-suggestion').length === 0){
            $('#disk_file_product_id').val("");
        }
    });
    

    【讨论】:

    • 这仅适用于较新版本的预输入插件。旧版本不支持命名事件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多