使用 Javascript 设置 innerHTML 与设置值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8823498/
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
Setting innerHTML vs. setting value with Javascript
提问by node ninja
When you want to use Javascript to change HTML, how do you know when to use either of the following?
当您想使用 Javascript 更改 HTML 时,您如何知道何时使用以下任一方法?
document.getElementById("randomNumber").value = number;
document.getElementById("randomNumber").innerHTML = number;
回答by Jay Tomten
Setting the value
is normally used for input/form elements. innerHTML
is normally used for div, span, td and similar elements.
设置value
通常用于输入/表单元素。innerHTML
通常用于 div、span、td 和类似元素。
Here is a link showing the use of ID.value: http://www.javascript-coder.com/javascript-form/javascript-form-value.phtml
这是一个显示使用 ID.value 的链接:http: //www.javascript-coder.com/javascript-form/javascript-form-value.phtml
回答by ThiefMaster
value
is for form elements, innerHTML
if you want to set the content of any other element.
There's also innerText
if you want to set the text content (you won't have to escape anything in there, but no HTML works in there)
value
用于表单元素,innerHTML
如果您想设置任何其他元素的内容。
还有innerText
如果你想设置文本内容(你不必在那里转义任何东西,但没有 HTML 工作在那里)
回答by Skyrim
value
is generally a property of specific i/o elements such as input
elements (also including the type="hidden"
).
value
通常是特定 i/o 元素的属性,例如input
元素(也包括type="hidden"
)。
elements which are not such as div, p, a, etc.
generally don't even have the value property and even if a value
is set, does not affect the final output.
不这样的元素div, p, a, etc.
通常甚至没有 value 属性,即使value
设置了 a ,也不影响最终输出。
回答by jjmontes
value
applies only to objects that have the value
attribute (normally, form controls).
value
仅适用于具有该value
属性的对象(通常为表单控件)。
innerHtml
applies to every object that can contain HTML (divs, spans, but many other and also form controls).
innerHtml
适用于每个可以包含 HTML 的对象(div、跨度,但还有许多其他和表单控件)。
They are not equivalent or replaceable. Depends on what you are trying to achieve...
它们不是等效的或可替换的。取决于你想要达到的目标......
回答by Daniel A. White
value
represents the value that would be GETed or POSTed for input
elements. innerHTML
could change the contents actual elements.
value
表示将为input
元素进行 GET 或 POST 的值。innerHTML
可以改变内容的实际元素。
回答by JuSchz
Value is for input
值用于输入
innerHTML for div and span
div 和 span 的innerHTML
回答by bballer320xu
Use .innerHTML to replace the entire inner body of the element with valid HTML you specify. A good example of this would be to place a nested div in an already existing div if an event occurs.
使用 .innerHTML 用您指定的有效 HTML 替换元素的整个内部主体。一个很好的例子是在发生事件时将嵌套的 div 放置在已经存在的 div 中。
Use .value for form elements that request a value, such as a text input.
将 .value 用于请求值的表单元素,例如文本输入。