为每个循环添加颜色更改 - JavaScript

时间:2017-10-25 20:10:43

标签: javascript loops colors

这是我第一次尝试编码 - 我甚至不知道我的问题是否有任何意义,请耐心等待我

无论如何,我编写了一个循环并显示数组的代码。

  

是否可以更改每个循环的文本颜色?

感谢大家的帮助:)。

<!DOCTYPE html>
<html>
<body>

<h2>Heroes & Their Ratings</h2> 
<p><font color="red">This will display some superheroes and their respective ratings:</font></p>
<p id="demo"> </p>


<script> //Starts loop script

var heroes = ["Batman 3", "Superman 4", "Wonderwoman 7", "Flash 10", "Spiderman 17", "Green Lantern 18", "Bat Girl 28","Thor 23","Captain 30","Punisher 2", "Blink 1","Amber 5","Spawn 6","Dart 8", "Destiny 9","Iceman 11", "Magma 12","Dr. Fate 13","Grifter 15","Ice 14","Katana 16","KidFlash 19","Nite Owl 20","Red Arrow 21","Raven 22","V 25","Wildcat 24","Zan 25","TNT 26","Terra 27"]; //Array so heroes variable stores multiple names
var text= '';
var i = 0 //Assigns i a value of 0
for (; i < heroes.length; i++) { // loop runs for every superhero
text += heroes[i] +  "<br>";
}
document.getElementById("demo").innerHTML = text;

//Ends loop script </script>



</body>
</html>

3 个答案:

答案 0 :(得分:3)

是的,有很多方法。其中一个是使用之前使用的字体标记:

&#13;
&#13;
var heroes = ["Batman 3", "Superman 4"];
var colors = ["blue", "green"];
var text= '';
for (var i = 0; i < heroes.length; i++) { // loop runs for every superhero
  text += "<font color='"+colors[i]+"'>"+heroes[i] +  "</font><br>";
}
document.getElementById("demo").innerHTML = text;
&#13;
<!DOCTYPE html>
<html>
<body>

<h2>Heroes & Their Ratings</h2> 
<p><font color="red">This will display some superheroes and their respective ratings:</font></p>
<p id="demo"> </p>

</body>
</html>
&#13;
&#13;
&#13;

但HTML5中的字体标记不支持。所以更好的方法是:

text += "<span style='color:"+colors[i]+"'>"+heroes[i] + "</span><br>";

答案 1 :(得分:0)

如果您是初学者,我可以为您提供简单的解决方案。

var colors = ["black","red","blue"...] //make colors array and enter color values for each hero
for (var i = 0; i < heroes.length; i++) {
  text += "<font color='"+ colors[i] +"'>"+ heroes[i] +  "</font><br>";
}

答案 2 :(得分:0)

如果您将颜色与英雄名称相关联,则可以更轻松地识别或修改每个英雄的名称。

&#13;
&#13;
    var heroes = [{name:"Batman 3", color:"green"}, {name: "Superman 4", color:"brown"}];
    for (var i=0; i < heroes.length; i++) {
    	document.getElementById("demo").innerHTML +=  "<div style='color:"+heroes[i].color+"'>" + heroes[i].name +  "</div>";
    }
&#13;
    <html>
    <body>
    <h2>Heroes & Their Ratings</h2> 
    <p><font color="red">This will display some superheroes and their respective ratings:</font></p>
    <p id="demo"> </p>
    </body>
    </html>
&#13;
&#13;
&#13;