我是JavaScript新手,我想从两个字段中获取一些文本。
用户单击确认后。文本打印在“结果”部分。
它没有按我预期的那样工作。确认后,您应该刷新一次页面,第二次可以使用!



var personalInfo = {
  firsName: document.getElementById("name").value,
  familyName: document.getElementById("family").value,
  confirm: function confirm() {
    document.getElementById("show-name").innerHTML = personalInfo.firsName;
    document.getElementById("show-family").innerHTML = personalInfo.familyName;
  }
}

<div> Basic Information</div>
<table>
  <tr>
    <td>First Name</td>
    <td><input type="text" id="name"></td>
    <td>Family Name</td>
    <td><input type="text" id="family"></td>
  </tr>
</table>
<button type="button" onclick="personalInfo.confirm()">Confirm</button>
<br><br><br><br><br><br><br><br><br>
<hr>
<div> Result!</div>
<table>
  <tr>
    <td>Name & Family name:</td>
    <td><span id="show-name"></span> <span id="show-family"></span></td>
  </tr>
</table>

最佳答案

在当前代码中,当声明personalInfo.firstName变量时,personalInfo.familyNamepersonalInfo设置为DOM元素的值。您应该将它们替换为在按下按钮时(运行personalInfo.confirm()时)获取DOM元素值的函数:



var personalInfo = {
  firstName: function () {return document.getElementById("name").value},
  familyName: function () {return document.getElementById("family").value},
  confirm: function() {
    document.getElementById("show-name").innerHTML = personalInfo.firstName();
    document.getElementById("show-family").innerHTML = personalInfo.familyName();
  }
}

<div> Basic Information</div>
<table>
  <tr>
    <td>First Name</td>
    <td><input type="text" id="name"></td>
    <td>Family Name</td>
    <td><input type="text" id="family"></td>
  </tr>
</table>
<button type="button" onclick="personalInfo.confirm()">Confirm</button>
<br>
<hr>
<h3> Result:</h3>
<div>Name: <span id="show-name"></span></div>
<div>Family name: <span id="show-family"></span></div>

10-07 19:05