繁体   English   中英

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

[英]How to append value of one input field into another input field's value with vanilla Javascript?

我有两个输入字段,我想将其中一个字段的值添加到另一个字段中。 这是我到目前为止所拥有的:

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);
}

所以 onClick,如果第二个输入字段的值是123 ,我期望第一个输入字段的值是www.google.com123 为什么portValue记录为undefined

appendPort不接收参数。 它应该使用getPort的返回值:

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

并且getPort应该返回它:

function getPort() {
    return document.getElementById('port').value;  // return something to be used by appendPort
}

首先是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>

portValue未定义,因为函数getPort不返回任何内容。 在函数末尾,添加行return portValue; 然后更改appendPort使其不接受输入并在开头添加此行var portValue = getPort();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM