代码之家  ›  专栏  ›  技术社区  ›  Ralph David Abernathy

如何使用vanilla Javascript将一个输入字段的值附加到另一个输入字段的值中?

  •  2
  • Ralph David Abernathy  · 技术社区  · 7 年前

    我有两个输入字段,我想把一个字段的值加到另一个字段上。以下是我目前掌握的情况:

    HTML

    <input id="server" type="text" value="www.google.com">
    <input id="port" type="text">
    <button onclick="appendPort()">Save</button>
    

    Javascript

    function getPort() {
      let portValue = document.getElementById('port').value;
    }
    
    function appendPort(portValue) {
      getPort();
      console.log(portValue);
    }
    

    www.google.com123 如果第二个输入字段的值为 123 . 为什么 portValue undefined ?

    3 回复  |  直到 7 年前
        1
  •  2
  •   ibrahim mahrir    7 年前

    appendPort 没有收到争论。它应该使用 getPort

    function appendPort() {
        var portValue = getPort();                     // get the value returned by getPort and store it in portValue
        console.log(portValue);
    }
    

    获取端口

    function getPort() {
        return document.getElementById('port').value;  // return something to be used by appendPort
    }
    
        2
  •  0
  •   S. Zee    7 年前

    首先,getPort中的portValue局部变量,因此它在appendPort函数中不活动。您应该将其用作全局。其次,在appendPort函数中使用portValue作为参数,因此它隐藏了原始的portValue。您在没有参数的情况下调用了appendPort,因此在函数中它将默认为未定义。

    <script>
    let portValue = 3; // set to global
    function getPort() {
       portValue = document.getElementById('port').value;
    }
    
    function appendPort() { // without parameter
      getPort();
      console.log(portValue);
    }
    </script>
    <input id="server" type="text" value="www.google.com">
    <input id="port" type="text">
    <button onclick="appendPort()">Save</button>
    
        3
  •  0
  •   kharhys    7 年前

    portValue getPort 不返回任何内容。在函数末尾,添加行 return portValue; 然后改变 appendPort 这样就不需要输入,在开头加上这一行 var portValue = getPort();