如何在JavaScript函数中从HTML输入中读取文本?

时间:2016-05-03 15:41:35

标签: javascript html css

在网页上,用户可以在文本字段中书写文字。我想使用此页面上的按钮阅读此文本,然后将其放在其他位置。这是迄今为止的简化标记:

<div id="Demo1" class="w3-accordion-content w3-container">
<h4>Let's make your Resume Header</h4>
<table>
  <tr>
    <th>Name</th>
    <td><input type="text" id="name"></td>
  </tr>
</table>
<button onclick="header()" class="save">SAVE</button>
</div>

这是我的JavaScript代码:

function header() {
  var name = document.getElementById(name).value;
  alert(name);
}

运行时,此警报根本不起作用。我无法弄清楚为什么,非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

您必须将elementById参数包装在引号中,并为HTML提供引用JavaScript的方法。见下文。

<script>
function header() {
  var name = document.getElementById("name").value;
  alert(name);
}
</script>

<div id="Demo1" class="w3-accordion-content w3-container">
<h4>Let's make your Resume Header</h4>
<table>
  <tr>
    <th>Name</th>
    <td><input type="text" id="name"></td>
  </tr>
</table>
<button onclick="header()" class="save">SAVE</button>
</div>

答案 1 :(得分:0)

你错过了报价。因此,请使用document.getElementById('name').value代替document.getElementById(name).value

如果您使用name作为参数,则可以不加引号使用它。

&#13;
&#13;
function header() {
  var name = document.getElementById('name').value;
  alert(name);
}
&#13;
<div id="Demo1" class="w3-accordion-content w3-container">
  <h4>Let's make your Resume Header</h4>
  <table>
    <tr>
      <th>Name</th>
      <td>
        <input type="text" id="name">
      </td>
    </tr>
  </table>
  <button onclick="header()" class="save">SAVE</button>
</div>
&#13;
&#13;
&#13;