如何在不写入当前文本的情况下将文本添加到文本框?

时间:2018-02-01 20:22:37

标签: javascript

我希望用户能够单击按钮并将文本添加到字段中,而不是覆盖它,并且还可以键入文本。

我该怎么做?

这是我到目前为止的代码:

<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>myStG review</title>
</head>

<script>
  function ButtonClick_Test() {
    document.getElementById("result").value = ' We loved working with Joe and Lorelei';
  }

  function addNoOne() {
    document.getElementById("result").value = ' No one is better.';
  }
</script>
</head>

<body>
  <form>
    <br/>
    <input type="button" value="We loved working with Joe and Lorelei" onclick="ButtonClick_Test()"> <br/>
    <input type="button" value="No one is better." onclick="addNoOne()"> <br/>
    <textarea type="text" id="result" rows="6" cols="60" onclick="this.focus();this.select()">
    </textarea>

  </form>
</body>

</html>

3 个答案:

答案 0 :(得分:3)

分配值时使用+ =运算符。像这样:

document.getElementById("result").value += ' We loved working with Joe and Lorelei';

另一个

同样的事情

答案 1 :(得分:1)

编辑:用另一个答案的+ =更新。 变化:

document.getElementById("result").value= ' No one is better.';

要:

document.getElementById("result").value += ' No one is better.';

&#13;
&#13;
function ButtonClick_Test()
{
document.getElementById("result").value = ' We loved working with Joe and Lorelei';
}

function addNoOne()
{
document.getElementById("result").value +=  ' No one is better.';
}
&#13;
<br/>
<input type="button" value="We loved working with Joe and Lorelei" onclick="ButtonClick_Test()"> <br/>
<input type="button" value="No one is better." onclick="addNoOne()"> <br/>
<textarea type="text" id="result" rows="6" cols="60" onclick="this.focus();this.select()">
</textarea>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

function addNoOne()
{
var old = document.getElementById("result").value;
document.getElementById("result").value = old + ' No one is better.';
}