简体   繁体   English

如何解决输入不退回的问题

[英]how to fix input from being returned backwards

For some reason when enter input its being returned in reverse. 由于某些原因,当输入输入时,它会反向返回。 I can get it to work using a for loop, but how would I do this using a while loop? 我可以使用for循环使其工作,但是如何使用while循环来实现呢?

 var input = document.getElementById('userinput').value;
 var i  = input.length;
 while (i--) {

    document.getElementById('message').innerHTML += input[i] + "<br/>";

  }

Either reverse the loop counter and condition: 反转循环计数器和条件:

var input = document.getElementById('userinput').value;
var i = 0;
while (i < input.length) {
  document.getElementById('message').innerHTML += input[i] + "<br/>";
}

Or reverse the order of concatenation inside the loop: 或反转循环内的串联顺序:

var input = document.getElementById('userinput').value;
var i  = input.length;
while (i--) {
  document.getElementById('message').innerHTML =
          input[i] + "<br/>" + document.getElementById('message').innerHTML;
}

Note that either way you shouldn't update .innerHTML in a loop: as a general principle try to minimise DOM updates, so use a temporary variable to build up the desired string and then assign .innerHTML once after the loop. 请注意,无论哪种方式都不应该在循环中更新.innerHTML :作为一般原则,请尽量减少DOM更新,因此请使用临时变量来构建所需的字符串,然后在循环分配一次.innerHTML Or for what you're actually doing here you don't need a loop: 或对于您在这里实际执行的操作,不需要循环:

var input = document.getElementById('userinput').value;
document.getElementById('message').innerHTML = input.split("").join("<br>");

Simplest way to achieve your goal: 实现目标的最简单方法:

var input = document.getElementById('userinput').value;
document.getElementById('message').innerHTML += input.split('').join('<br/>')

Here's a different approach using split and forEach 这是使用split和forEach的另一种方法

var input = document.querySelector("#userinput").value;
var html = "";

input.split("").forEach(function(char){

  html += char + "<br>";

});

document.querySelector("#message").innerHTML = html;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM