![](/img/trans.png)
[英]what does document.createElement('a') do in this code?
[英]Why does `document.createElement` do not allow the creation of self-closing tags?
示例 JavaScript
<html>
<body>
<form id="test"></form>
</body>
</html>
let input_el = document.createElement('input');
input_el.setAttribute('type','text');
input_el.setAttribute('name','your_name');
let my_form = document.getElementById('test');
my_form.prepend(input_el);
在 windows(chrome 版本 96.0.4664.45)上的 chrome 開發人員工具中生成以下 output:
而不是正確的形式:
<input type="text" name="your_name">
另見這個小提琴: https://jsfiddle.net/m1fqzLv6/
目前我沒有找到任何允許這樣做的 javascript function。
這個問題是基於document.createElement()
會產生 HTML 代碼的假設。 這是不正確的。
實際上,HTML 代碼被解析成文檔 object model (DOM)。 JavaScript 可以隨后修改 DOM(另見上面 TJ Crowder 的評論)。 在您的示例中,添加了一個<input>
元素。
Chrome 在其開發者工具中,通過 HTML 代碼表示 DOM,大多數開發者都可以輕松閱讀。 如果 DOM 中有<input>
元素,則開發工具面板必須決定如何表示它。 顯然,它選擇帶有<input></input>
的長格式。 然而,這只是 output 決定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.