<p>仅显示最后分配的值

时间:2018-07-04 21:56:20

标签: javascript html

我有一个代码,在其中我尝试通过随机化字符(强行使用字符串)来获得所需的字符串(“嘿!”),并在<p>(下一步将覆盖上一个)。但是问题是,在#first中,仅显示排列的最后一步(“嘿!”)。

为什么不一步一步显示所有步骤,只显示最后一步?对于该问题的任何帮助,我们将不胜感激。

注意:在控制台中,记录了所有步骤。我也尝试使用<p>timeout中输出字符串;没什么改变。

必须是的示例https://i.imgur.com/fNjhjUS.gif

这是我的Javascript代码和HTML:

var fline = ["H", "e", "y", "!"];
    temp_fline = [" ", " ", " ", " "],
    index = 0,
    possible = "!abc!defghijklmnopqrstuvwxyz!ABCDEFGHIJKLMNOPQRSTUVWXYZ!";

while (index < 4)
{
    if (fline[index] != temp_fline[index])
        temp_fline[index] = possible[Math.round(Math.random() * 57)];

    if (fline[index] == temp_fline[index])
        ++index;

    var tempString = "";
    for (var i = 0; i < 4; ++i)
        tempString += temp_fline[i];

    console.log(tempString);
    document.getElementById("fline").innerHTML = '> ' + tempString;
}
<html>
<body>
    <div id="first">
        <br>
        <p id="fline"></p>
        <br><br><br>
        <p id="sline"></p>
        <br><br><br>
        <p id="tline"></p>
        <br><br><br>
        <p id="fhline"></p>
    </div>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

您将在每次循环迭代中覆盖innerHTML,而不是添加到其中

尝试更改

document.getElementById("fline").innerHTML = '> ' + tempString;

收件人

document.getElementById("fline").innerHTML += '> ' + tempString;
                                        // ^^ concatenate instead of reassign

答案 1 :(得分:1)

想要那样吗?

	var fline = ["L", "i", "k", "e", " ", "t", "h", "i", "s", "?"], count = 0, index = 0, flist = [],
    possible = "!abc!?defghijklmnopqrstuvwxyz!ABCDEFGHIJKLMNOPQRSTUVWXYZ! ";

	let found = document.getElementById("found");
	let checking = document.getElementById("checking");
	
	let timer = setInterval(function ()
	{
		if (index >= fline.length)
		{
			console.log(flist);
			clearInterval(timer);
			checking.innerText = "";
			flist = [];
		}
		else
		{
			if (fline[index] == possible[count])
			{
				found.innerText += possible[count];
				flist.push(possible[count]);
				index++; count = 0;
			}
			else
			{
				checking.innerText = possible[count];
				count++;
			}
		}
	}, 24);
<div><b id="found"></b><i id="checking"></i></div>