Html 使用纯 Javascript 创建输入字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17234209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create an input field using pure Javascript
提问by Enrique Moreno OB
Im trying to create such element only with JS:
我试图只用 JS 创建这样的元素:
<input type="text" value="default">
To do so, I tried this code:
为此,我尝试了以下代码:
var mi = document.createElement("input");
mi.type= "text"
mi.value = "default"
But when I run it in Chrome Dev Tools, it only creates this element:
但是当我在 Chrome Dev Tools 中运行它时,它只会创建这个元素:
<input type="text">
What am I missing?
我错过了什么?
回答by Paul S.
Setting a propertyof a HTMLElementisn't exactly the same as setting it's attributeto the same thing.
设置一个物业一的HTML元素是不完全一样的,因为它的设置属性,以同样的事情。
You most likely wanted to use element.setAttribute
您很可能想使用 element.setAttribute
var mi = document.createElement("input");
mi.setAttribute('type', 'text');
mi.setAttribute('value', 'default');
Now you can see
现在你可以看到
new XMLSerializer().serializeToString(mi);
// "<input type="text" value="default">"
In your example, the valuedisplayed by the <input>
will still be default
, it just isn't set as the attribute.
在您的示例中,显示的值<input>
仍然是default
,只是没有设置为属性。
Further note that if the user changes the valueof <input>
, e.g. types into it, setting the attributewill not change the valueany longer, but setting the valueproperty will still change it. Again, this is because an attributeis different to a property.
还应注意的是,如果用户更改值的<input>
,如类型进去,设置属性不会改变数值的任何时间较长,但设置值属性将改变它。同样,这是因为attribute与property不同。
回答by karthi
var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");
i.setAttribute('value',"default");
回答by Cyrille Armanger
I think you are missing the ; after "text".
我认为你错过了; 在“文本”之后。