如何使用JavaScript刷新HTML5数据表? [英] How do you refresh an HTML5 datalist using JavaScript?

查看:148
本文介绍了如何使用JavaScript刷新HTML5数据表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在动态地将选项加载到HTML5 datalist 元素中。但是,浏览器会在加载选项之前尝试显示 datalist 。这导致列表未被显示或者有时显示部分列表。有没有办法在加载选项后通过JavaScript刷新列表?

I'm loading options into an HTML5 datalist element dynamically. However, the browser attempts to show the datalist before the options have loaded. This results in the list not being shown or sometimes a partial list being shown. Is there any way to refresh the list via JavaScript once the options have loaded?

HTML

<input type="text" id="ingredient" list="ingredients">
<datalist id="ingredients"></datalist>

JavaScript

$("#ingredient").on("keyup", function(event) {
    var value = $(this).val();
    $.ajax({
        url: "/api/ingredients",
        data: {search: value.length > 0 ? value + "*" : ""},
        success: function(ingredients) {
            $("#ingredients").empty();
            for (var i in ingredients) {
                $("<option/>").html(ingredients[i].name).appendTo("#ingredients");
            }
            // Trigger a refresh of the rendered datalist
        }
    });
});

注意:在Chrome和Opera中,仅当用户点击输入后才会显示整个列表输入文字。但是,我希望整个列表显示用户类型。 Firefox不是问题,因为它似乎在更新选项时自动刷新列表。

Note: In Chrome and Opera, the entire list is only shown if the user clicks on the input after entering text. However, I'd like the entire list to appear as the user types. Firefox is not a problem, as it appears to refresh the list automatically when the options are updated.

更新

我不确定这个问题是否有令人满意的答案,因为我认为这只是某些浏览器的缺点。如果更新 datalist ,浏览器刷新列表,但某些浏览器(包括Chrome和Opera)根本不这样做。黑客?

I'm not sure this question has a satisfactory answer, as I believe this is simply a shortcoming of certain browsers. If a datalist is updated, the browser should refresh the list, but some browsers (including Chrome and Opera) simply do not do this. Hacks?

推荐答案

问题很长一段时间后我找到了IE和Chrome的解决方法(未在Opera上测试过,已经确定对于Firefox)。

Quite a long time after question but I found a workaround for IE and Chrome (not tested on Opera and already OK for Firefox).

解决方案是在成功(或完成)功能结束时将输入集中在这样:

The solution is to focus the input at the end of success (or done) function like this :

$("#ingredient").on("keyup", function(event) {
var _this = $(this);
var value = _this.val();
$.ajax({
    url: "/api/ingredients",
    data: { search: value.length > 0 ? value + "*" : "" },
    success: function(ingredients) {
        $("#ingredients").empty();
        for (var i in ingredients) {
           $("<option/>").html(ingredients[i].name).appendTo("#ingredients");
        }
        // Trigger a refresh of the rendered datalist
        // Workaround using focus()
        _this.focus();
    }
});

适用于Firefox,Chrome和IE 11+(可能是10个)。

It works on Firefox, Chrome and IE 11+ (perhaps 10).

这篇关于如何使用JavaScript刷新HTML5数据表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆