使用 JavaScript 设置 HTML5 输入列表值 [英] set HTML5 input list value with JavaScript
问题描述
我将通过 JavaScript 创建一个带有附加数据列表的 html5 输入字段.我在创建这些 dom 节点时没有遇到任何问题,但是我在使用纯 JavaScript 设置 list
属性值时遇到了问题.这可能吗?我已经检查了节点的功能,并且 list
的值在那里,但是每当我尝试设置它时,都不会分配新的值.有人有什么想法吗?
I'm to create a html5 input field with an attached datalist by JavaScript. I'm not having any issues creating these dom nodes, but I am having trouble setting the list
attribute value using pure JavaScript. Is this possible? I've checked the functionality of the node and the value of list
is there, but whenever I try and set it no new value is assigned. Does anybody have any ideas?
这里是代码示例.
var _form = document.body.appendChild(document.createElement('form')),
_input = _form.appendChild(document.createElement('input')),
_datalist = _form.appendChild(document.createElement('datalist'));
_input.list = 'exampleList';
_input.datalist_id = 'exampleList';
_input.className = 'getme';
_datalist.id = 'exampleList';
for (var i = 0; i < 5; i++) {
var _option = _datalist.appendChild(document.createElement('option'));
switch(i){
case i:
_option.value = i;
break;
};
};
编辑
我找到了一种通过 element.setAttribute();
方法执行此操作的方法.如何使用类似于(例如)element.className = 'value';
.
I have found a method of doing this via the element.setAttribute();
method. How would one go about doing this in a syntax similar to (for example) element.className = 'value';
.
先谢谢你!
推荐答案
根据 MDN 没有直接设置属性的属性.所以看起来你被困在 setAttribute()
According to MDN there is no property to set that attridute directly. So it looks like you're stuck with setAttribute()
您还应该注意 DOM 操作会带来一些性能问题 所以它是有时最好将它们最小化.您可能需要考虑以下事项:
You should also note that DOM manipulations come with some performance ovehead so it is some times best to minimise them. You might want to consider the following:
var _form = document.body.appendChild(document.createElement('form')),
_input = _form.appendChild(document.createElement('input')),
_datalist = _form.appendChild(document.createElement('datalist'));
_datalist.id = 'exampleList';
_input.setAttribute('list','exampleList');
var _option = "";
for (var i = 0; i < 5; i++) {
_option += "<option value='" + i + "' />";
};
_datalist.innerHTML = _option;
这篇关于使用 JavaScript 设置 HTML5 输入列表值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!