Javascript JS 中“.innerHTML”和“.value”的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31225901/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:24:48  来源:igfitidea点击:

Difference between ".innerHTML" and ".value" in JS

javascript

提问by Jun Q

I am confused on what is the difference between .innerHTMLand .valuein JavaScript. Here is my code:

我对JavaScript.innerHTML.valueJavaScript之间的区别感到困惑。这是我的代码:

<body>
Input string: <input type="text" id="input" />
....
</body>

When I use this code I cannot get the content of input string:

当我使用此代码时,我无法获取输入字符串的内容:

var str=document.getElementById("input").innerHTML;

While I use the following code, it works:

当我使用以下代码时,它可以工作:

var str=document.getElementById("input").value;

Any one knows what is the difference between them?

有谁知道它们之间有什么区别?

回答by jax

valuerefers to the value of an input element (or textearea)

value指输入元素(或 textearea)的值

<input value="hello world">

value would be "hello world"(or any value typed inside)

值将是"hello world"(或在里面输入的任何值)



innerHTMLrefers to the contents inside an HTML element.

innerHTML指的是 HTML 元素内的内容。

<div>
  <span class="hello">
     All tags and their children are include in innerHTML.
  </span>
  All this is part of innerHTML.
</div>

innerHTML of the div tag would be the string:

div 标签的 innerHTML 将是字符串:

  '<span class="hello">
     All tags and their children are include in innerHTML.
  </span>
  All this is part of innerHTML.'

回答by David W

The .innerHTML property refers to the literal HTML markup that is, once assigned, interpreted and incorporated into the DOM (Document Object Model) for the current document. On the other hand, the .value property simply refers to the content of typically an HTML input control, such as a textbox. Not every HTML element supports the input property, whereas most if not all support the innerHTML property.

.innerHTML 属性是指文字 HTML 标记,一旦分配、解释并合并到当前文档的 DOM(文档对象模型)中。另一方面,.value 属性仅指典型的 HTML 输入控件的内容,例如文本框。并非每个 HTML 元素都支持 input 属性,而大多数(如果不是全部)都支持 innerHTML 属性。

回答by Himani

.value gives you the currently-set value of a form element (input, select, textarea), whereas .innerHTML builds an HTML string based on the DOM nodes the element contains.

.value 为您提供表单元素(input、select、textarea)的当前设置值,而 .innerHTML 根据元素包含的 DOM 节点构建 HTML 字符串。