如何使用Javascript使用来自输入文本框的输入填充div? [英] How can I use Javascript to populate a div with input from an input text box?
问题描述
我正在尝试在填充div的输入文本框中运行脚本.该代码段如下所示:
I'm trying to run a script on an input text box that populates a div. The snippet is like so:
<input type="text" id="control" value="" />
<div id="displaydiv"></div>
<script>
document.getElementById("control").onkeydown = function() {
document.getElementById("displaydiv").innerHTML = this.value;
}
</script>
这里的问题是有一个字符的滞后,即如果我键入"a",则什么都不会显示.当我键入"b"时,将显示前一个"a",依此类推.我尝试用onkeyup代替onkeydown,但是仍然有些滞后.如何在不刷新页面和/或失去对输入框的关注的情况下使div实时匹配输入文本框?
The problem here is that there is a lag of one character, i.e. if I type 'a', nothing shows up. When I type 'b', the previous 'a' shows up and so on. I tried replacing the onkeydown with onkeyup, and there is still a bit of a lag. How do I get the div to match the input text box in real time, without refreshing the page and/or losing focus on the input box?
感谢您的光临.
推荐答案
这是因为onkeydown
在键将其值添加到输入之前触发.使用onkeyup
代替.它将按照您想要的方式工作.
That is because onkeydown
triggers before the key has added its value to the input. Use onkeyup
instead. It will work the way you are after.
编辑:不确定我是否错过了速度,是否编辑了问题,但是不可避免的会出现滞后现象.正如您将要获得的,它与实时"非常接近.甚至还没有那么糟,当我在 a小提琴
Not sure if I missed the speed thing, if you edited your question, but the lag you are seeing is unavoidable. It is as close to "real-time" as you are going to get. It's really not even that bad, less than half a second when I check it in a fiddle
Edit2 :为了满足我的好奇心,我对照KnockoutJS的数据绑定检查了性能,一个输入通过敲除更新了一个div文本,另一个输入通过脚本更新了一个div.性能是相同的.实际上,让我感到有些惊讶的是淘汰赛并没有带来任何明显的开销.这是小提琴
Edit2: Just to satisfy my curiosity, I checked the performance against KnockoutJS's databinding, with the one input updating a div text via knockout, and another div via your script. The performance is identical. I was actually a bit surprised knockout didn't introduce any noticable overhead. Here is the fiddle
这篇关于如何使用Javascript使用来自输入文本框的输入填充div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!