[英]Create an input field using pure Javascript
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? 我想念什么?
Setting a property of a HTMLElement isn't exactly the same as setting it's attribute to 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 value displayed by the <input>
will still be default
, it just isn't set as the attribute . 在您的示例中,
<input>
显示的值仍将是default
,只是未将其设置为attribute 。
Further note that if the user changes the value of <input>
, eg types into it, setting the attribute will not change the value any longer, but setting the value property will still change it. 还要注意,如果用户更改了
<input>
的值 (例如键入),则设置属性将不再更改该值 ,但设置value属性仍将对其进行更改。 Again, this is because an attribute is different to a property . 同样,这是因为属性不同于属性 。
var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");
i.setAttribute('value',"default");
I think you are missing the ; 我想你错过了; after "text".
在“文本”之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.