如何连续将键入的字符添加到变量? [英] How to continually add typed characters to a variable?

查看:70
本文介绍了如何连续将键入的字符添加到变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道如何在不删除变量先前数据的情况下将用户按下的字符添加到变量中.例如,当用户键入a时,它将a添加到变量中.然后,用户键入t并将t添加到变量中,但保存了a,因此现在变量是包含at的字符串.我已经尝试了很长时间了,但仍然不知道该怎么做.

I need to know how to add the character a user pressed to a variable without erasing the variables previous data. For example, when a user types a it adds a to a variable. Then the user types t and it adds t to the variable, but it saves the a, so now the variable is a string containing at. I have tried for quite awhile now and still can not figure out how to do this.

推荐答案

您可以利用oninput事件,创建一个undefined变量,在第一个input事件中,设置window[variable]并将创建的变量设置为character用户输入;在用户的后续输入中,使用参数-1

You can utilize oninput event, create a variable that is undefined, at first input event, set window[variable] and created variable to character user input; at subsequent input from user, concatenate window[variable] from last character at user input using String.prototype.slice() with parameter -1

var q = void 0;

document.querySelector("input").oninput = function(e) {
  if (!q && !window[e.target.value]) {
    window[e.target.value] = q = e.target.value;
  } else {
    window[q] += e.target.value.slice(-1);
    console.log(window[q])
  }
}

<input type="text" />

这篇关于如何连续将键入的字符添加到变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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