在网页上,用户可以在文本字段中写入文本。我想使用此页面上的按钮来阅读此文本,然后将其放在其他地方。这是到目前为止的简化标记:
<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);
}
当我运行此警报时,它根本不起作用。我不明白为什么,非常感谢任何帮助。
最佳答案
您错过了引号。因此,请使用 document.getElementById('name').value
而不是 document.getElementById(name).value
。
如果您使用 name
作为参数,那么您可以在不带引号的情况下使用它。
function header() {
var name = document.getElementById('name').value;
alert(name);
}
<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 - 如何从 JavaScript 函数中的 HTML 输入中读取文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37008566/