Javascript:用文本填充输入,而不会覆盖已经存在的文本 [英] Javascript: filling inputs with text without overwriting the text that is already there

查看:71
本文介绍了Javascript:用文本填充输入,而不会覆盖已经存在的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个按钮,在单击该按钮时将文本添加到输入中,但是它没有添加文本,而是覆盖了已经在其中键入的文本.我需要帮助. 这是代码:

I am trying to create a button that adds text to input when clicked, but instead of adding text it overwrites the text that's already typed in there. I need help. Here's the code:

<script>
  function autoFill() {
    var input = document.getElementsByTagName("INPUT")[0]

    input.value = "text overwrites instead of adding";
  }
</script>

<input type="input"></input>
<button type="button" onclick="autoFill()">fill it!</button>

推荐答案

我应该像这样简单:

input.value += "text overwrites instead of adding";

+ = 运算符将某些内容添加到变量中,而 = 则分配了新值.

The += operator adds something to a variable while = assigns a new value.

图片:

var a=8;
a+=4;
console.log(a);

痕迹12

如果我们这样做:

var a=8;
a=4;
console.log(a);

痕迹4

这篇关于Javascript:用文本填充输入,而不会覆盖已经存在的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆