JS中".innerHTML"和".value"的区别

Jun*_*n Q 9 javascript

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

<body>
Input string: <input type="text" id="input" />
....
</body>
Run Code Online (Sandbox Code Playgroud)

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

var str=document.getElementById("input").innerHTML;
Run Code Online (Sandbox Code Playgroud)

虽然我使用以下代码,但它的工作原理:

var str=document.getElementById("input").value;
Run Code Online (Sandbox Code Playgroud)

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

jax*_*jax 19

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

<input value="hello world">
Run Code Online (Sandbox Code Playgroud)

值将是"hello world"(或内部输入的任何值)


innerHTML 指的是HTML元素中的内容.

<div>
  <span class="hello">
     All tags and their children are include in innerHTML.
  </span>
  All this is part of innerHTML.
</div>
Run Code Online (Sandbox Code Playgroud)

div标签的innerHTML将是字符串:

  '<span class="hello">
     All tags and their children are include in innerHTML.
  </span>
  All this is part of innerHTML.'
Run Code Online (Sandbox Code Playgroud)


Dav*_*d W 3

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