如何连续将键入的字符添加到变量? [英] How to continually add typed characters to a variable?
问题描述
我需要知道如何在不删除变量先前数据的情况下将用户按下的字符添加到变量中.例如,当用户键入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屋!