【问题标题】:'charAt' 'for loop' issue'charAt' 'for 循环' 问题
【发布时间】:2017-11-15 13:26:54
【问题描述】:

我将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 的性质,或者循环有问题。

我觉得它只是替换了字符,所以我什至插入了一个换行符,但似乎没有帮助。

提前致谢!

【问题讨论】:

  • 追加不要替换:outp.innerHTML += res + '\n';(另请注意大写L)
  • 您正在替换输出。你需要追加
  • 另外,innerHTML 不是 innerHTMl
  • 另外,最好更新一次innerHTML,而不是循环。首先将逻辑应用于字符串变量,最好使用split 和join。
  • 或只是outp.innerHTML = inp.split('').join('\n');

标签: javascript for-loop char


【解决方案1】:

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

innerHTML 也有错字。你写了innerHTMl。并且,关于这一点,当您一开始不会添加 HTML 时,不要使用 .innerHTML,而是在这种情况下使用 textContent,因为使用 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
<input id="inp" value="ABCDEFG">
<div id="display"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 2014-03-19
    • 2020-09-15
    • 2011-01-26
    • 1970-01-01
    相关资源
    最近更新 更多