我试图在它们飞行时创建一个数据列表,并将其附加到现有的输入元素上。但是什么也没发生(没有显示下拉箭头)
jQuery也可以接受。

var optionList = ["Seattle", "Las Vegas", "New York", "Salt lake City"];

function fillDataList() {
    var container = document.getElementById('my-text-box'),
    i = 0,
    len = optionList.length,
    dl = document.createElement('datalist');

    dl.id = 'dlCities';
    for (; i < len; i += 1) {
        var option = document.createElement('option');
        option.value = optionList[i];
        dl.appendChild(option);
    }
    container.appendChild(dl);
}

小提琴:
https://jsfiddle.net/tomsx/704cxako/

(示例取自本网站:
http://blogs.microsoft.co.il/gilf/2012/07/30/quick-tip-autocomplete-using-html5-datalist-element/)

最佳答案

您必须将输入元素的list属性设置为数据列表的ID:

<input id="my-text-box" list="dlCities"/>

工作代码示例:

var optionList = ["Seattle", "Las Vegas", "New York", "Salt lake City"];

function fillDataList() {
    var container = document.getElementById('my-text-box'),
    i = 0,
    len = optionList.length,
    dl = document.createElement('datalist');

    dl.id = 'dlCities';
    for (; i < len; i += 1) {
        var option = document.createElement('option');
        option.value = optionList[i];
        dl.appendChild(option);
    }
    container.appendChild(dl);
}
fillDataList();
<input id="my-text-box" list="dlCities"/>


或:如果您不想修改HTML,则可以使用 Element.setAttribute() 在JavaScript中设置属性:
container.setAttribute('list','dlCities');

var optionList = ["Seattle", "Las Vegas", "New York", "Salt lake City"];

function fillDataList() {
    var container = document.getElementById('my-text-box'),
    i = 0,
    len = optionList.length,
    dl = document.createElement('datalist');
    container.setAttribute('list','dlCities'); // Set the attribute here

    dl.id = 'dlCities';
    for (; i < len; i += 1) {
        var option = document.createElement('option');
        option.value = optionList[i];
        dl.appendChild(option);
    }
    container.appendChild(dl);
}
fillDataList();
<input id="my-text-box"/>

关于javascript - 动态创建HTML5数据列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52397664/

10-09 23:59