How can I use Javascript to populate a div with in

2019-07-25 01:26发布

问题:

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>

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?

Thanks for looking.

回答1:

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.

Edit: 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: 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