简体   繁体   English

如何在.innerHTML(for-loop)中迭代字符串的每个字符?

[英]How to iterate each character of a string in .innerHTML (for-loop)?

Hi let's assume that I have the following code: 您好,假设我有以下代码:

var information_paragraph = document.getElementById(myDivElement);
var infoText = "Hello World!";
information_paragraph.innerHTML = infoText;

So instead of adding the whole string "Hello World!", I was thinking if I can add a char of that string one at a time. 因此,我在考虑是否可以一次添加一个字符串的一个字符,而不是添加整个字符串“ Hello World!”。 How to access the characters of the string and create a for loop to add content in the innerHTML rather than replacing it? 如何访问字符串的字符并创建for循环以在innerHTML中添加内容,而不是替换它?

Convert string to array and iterate? 将字符串转换为数组并进行迭代?

 document.getElementById('block').innerHTML.split('').forEach(function(i){ console.log(i); }); 
 <div id="block">Text</div> 

I think what you want is to use the string as array and append it to the inner html if you ant it all in a sane line remove "</br>"+ 我认为您想要的是使用字符串作为数组,并将其附加到内部html(如果您以合理的方式将其全部删除),请删除"</br>"+

 var information_paragraph = document.getElementById("myDivElement"); var infoText = "Hello World!"; for(i = 0; i < infoText.length; i++) information_paragraph.innerHTML += "<br/>"+infoText[i]; 
 <div id="myDivElement"> </div> 

I think may this work 我认为这可能有效

const  information_paragraph = 
document.getElementById('myDivElement');
let  infoText = "Hello World!"; 
let infoTextLetters ;
for(i in infoText){
  infoTextLetters +=  `
   <br> ${infoText[i]} ` ;

information_paragraph.innerHTML = infoTextLetters

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

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