在 JavaScript 中创建的元素添加 .type 和 .disabled 属性但不添加 .form 或 .value

Element created within JavaScript adds .type and .disabled attribute but not .form or .value

我正在 JavaScript 中创建一个用于填充 <li> 元素的函数中的元素。

从控制台我可以看到我正在创建的 <input> 元素正在创建,并且被正确地附加到包含它的 <div> ,但缺少一些属性,即:

我已经使用console.log()(如下所示)进行了调试,以确认上述两个值确实存在,但它们并未提供给我正在创建的元素。


下面是我的代码片段:

var inputProj = document.createElement("input");
console.log("day" + dayNumber + "Form");
inputProj.form = "day" + dayNumber + "Form";
inputProj.type = "text";
console.log(response.data.data.variables.input.projects.items[0].projectNumber);
inputProj.value = response.data.data.variables.input.projects.items[0].projectNumber;
inputProj.disabled = "disabled";

console.log("inputProj: ");
console.log(inputProj);

proj.appendChild(inputProj);
console.log(proj);

我从控制台得到的输出是:

day4Form
888843
inputProj:
<input type="text" disabled>
<li id="fProjects4"><input type="text" disabled></li>

因此可以看出,只有 .type.disabled 属性被赋予 <input> 元素。

我无法确定为什么没有为元素提供 .form.value 属性。

这是两种不同的属性,一种是 DOM 属性,另一种是 JavaScript 对象属性。以下应该有效:

var inputProj = document.createElement("input");
var formAttribute = document.createAttribute("form");
formAttribute.value = "day" + dayNumber + "Form";
inputProj.setAttributeNode(formAttribute);

此页面的一小段引述:https://javascript.info/dom-attributes-and-properties

In HTML language, tags may have attributes. When the browser reads HTML text and creates DOM objects for tags, it recognizes standard attributes and creates DOM properties from them.

So when an element has id or another standard attribute, the corresponding property gets created. But that doesn’t happen if the attribute is non-standard.

该页面包含很多有趣且有用的信息。值得一看。

你试过.setAttribute功能了吗? 示例:inputProj.setAttribute("type", "text");