即时创建 HTML5 数据列表 [英] Creating a HTML5 datalist on the fly
问题描述
我正在尝试动态创建数据列表并将其附加到现有的输入元素.但没有任何反应(没有显示下拉箭头)jQuery 也是可以接受的.
I'm trying to create a datalist on they fly and attach it to an existing input element. But nothing happens (no dropdown arrow is shown) jQuery would be acceptable, too.
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/ )
(Example taken from this site: http://blogs.microsoft.co.il/gilf/2012/07/30/quick-tip-autocomplete-using-html5-datalist-element/ )
推荐答案
你必须将 input 元素的 list
属性设置为 datalist 的 id:
You have to set the input element's list
property as the id of the datalist:
<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"/>
OR:如果您不想修改 HTML,可以使用 Element.setAttribute()
在 JavaScript 中设置属性:
OR: If you do not want to modify the HTML, you can use Element.setAttribute()
to set the attribute in 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"/>
这篇关于即时创建 HTML5 数据列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!