简体   繁体   English

输入元素中 textContent 的目的是什么?

[英]What is the purpose of textContent in an input element?

Provided an input element in a DOM, it does have a textContent property along with value .在 DOM 中提供一个 input 元素,它确实有一个textContent属性和value It is well known that the value of the input is what shown in the text box, and this element cannot have any children, that is <input>something</input> still gives an empty input followed by a sibling text node, whereas closing tag is completely ignored.众所周知,输入的值是文本框中显示的值,并且该元素不能有任何子元素,即<input>something</input>仍然给出一个空输入,后跟一个兄弟文本节点,而关闭标签完全被忽略。 But when we set a value to the textContent of this input, it is somehow survives the round-trip:但是当我们为此输入的textContent设置一个值时,它以某种方式在往返过程中幸存下来:

input.textContent = 'something'
console.log(input.textContent)  // this works

Also, after setting the property, the input appear as having child elements in the inspector:此外,设置属性后,输入在检查器中显示为具有子元素: 设置文本内容后的Safari检查器截图

Maybe it's just me, but I fail to see any logical consistency here.也许这只是我,但我在这里看不到任何逻辑一致性。 Wouldn't it be nice to have a Type Error on setting text content to the input?在将文本内容设置为输入时出现类型错误不是很好吗?

Is there any reasoning behind present behaviour?目前的行为背后有什么原因吗?

The DOM is not HTML, but an API for tree structures that comply with the XML information set Translating <input>something</input> into an input element followed by a text node is the behaviour of the HTML parser, not the behaviour of the DOM. DOM是不是HTML,但对于树结构,其与符合的API XML信息设置翻译<input>something</input>到输入元件后跟文本节点是HTML解析器的行为,而不是的行为DOM。

In fact, if you use XHTML, served as application/xhtml+xml , <input>something</input> will become an input element with a text node child, the same as using .textContent .实际上,如果您使用 XHTML,作为application/xhtml+xml<input>something</input>将成为带有文本节点子节点的输入元素,与使用.textContent相同。 So it's entirely normal that .textContent works the way it does.所以.textContent以它的方式工作是完全正常的。

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

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