简体   繁体   English

无论如何,在运行时是否将数据列表与js中的输入动态关联?

[英]Is there anyway to dynamically associate a datalist with an input in js at runtime?

I am unable to associate a datalist with an input using js, however I am able to if I manually add the list attribute using the document inspector in Chrome. 我无法使用js将数据列表与输入相关联,但是如果我使用Chrome中的文档检查器手动添加列表属性,则可以。

After doing a bit of research, I stumbled on the fact that the list property is read-only, http://msdn.microsoft.com/en-us/library/ie/hh772937(v=vs.85).aspx . 经过一些研究,我偶然发现list属性是只读的, http://msdn.microsoft.com/en-us/library/ie/hh772937(v=vs.85).aspx Does this mean that it is impossible to associate a datalist using js or am I using the wrong property? 这是否意味着无法使用js关联数据列表,还是我使用了错误的属性?

I am creating my inputs and datalists dynamically at runtime as part of a javascript library I am making so I am unable to attach the datalist in the normal way. 我将在运行时动态创建我的输入和数据列表,这是我正在制作的javascript库的一部分,因此无法以常规方式附加数据列表。

 //Please open console var myTextInput = document.getElementById('myTextInput'), myDataList = document.getElementById('myDataList'); myTextInput.list = 'myDataList'; console.log(myTextInput.list); //Outputs: null myTextInput.list = myDataList.id; console.log(myTextInput.list); //Outputs: null myTextInput.list = myDataList; console.log(myTextInput.list); //Outputs: null 
 <form> <input type="text" id="myTextInput" /> <datalist id="myDataList"> <option value="1" /> <option value="2" /> <option value="3" /> </datalist> </form> 

Use setAttribute() - works for me in Firefox and Chrome: 使用setAttribute() -适用于Firefox和Chrome:

myTextInput.setAttribute('list', 'myDataList');

I don't know if you have jQuery available, but if you do the jQuery version would be: 我不知道您是否有可用的jQuery,但如果您使用jQuery,则版本为:

$(myTextInput).attr('list', 'myDataList');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM