'charAt''for loop'问题

时间:2017-06-13 16:33:38

标签: javascript for-loop char

我将charAt()置于for循环中以获取输入框inp中输入的字符,并在textarea outp中显示输出。

var inp = document.getElementById('inp').value;
var outp = document.getElementById('display');
for(x = 0;x<inp.length;x++){
    var res = inp.charAt(x);
    outp.innerHTML = res + "\n";
}

由于某种原因,它只打印输入中的最后一个字符,而不是打印输入的每个字母。我猜这是charAt的本质,或者循环有问题。

我觉得它只是替换了角色,所以我甚至插入换行符但似乎没有帮助。

提前致谢!

1 个答案:

答案 0 :(得分:1)

这样做是因为您正在打印x并且x始终是最新的循环索引,并且您将innerHTML设置为仅一个字符。您需要将该字符连接到前一个字符串的末尾。

您还有innerHTML的拼写错误。你写了innerHTMl。而且,关于这一点,当你不首先添加HTML时不要使用.innerHTML,而是在类似的情况下使用textContent,因为使用{{1}会有更多的性能开销比innerHTML

textContent
// Don't set your variables to a property of a DOM element. Set them to the 
// element itself. This way, if you ever need a different proeprty value, you
// won't have to re-scan the DOM for the same element again.
var inp = document.getElementById('inp');
var outp = document.getElementById('display');


var output = ""; // This will hold the built up string

for(x = 0; x < inp.value.length;x++){
    var res = inp.value.charAt(x);
    output += res + "\n";  // concatenate with +=
}

outp.textContent = output; // update the dom as little as possible

相关问题