Javascript 打印下面突出显示的文本,每次打印一个字符,每个字符之间的显示延迟为10毫秒

Javascript 打印下面突出显示的文本,每次打印一个字符,每个字符之间的显示延迟为10毫秒,javascript,html,Javascript,Html,当我点击按钮时,它不会运行 添加一个id为btnPrint、值为“Print”的按钮和一个名为printString()的事件处理程序 添加用于增量接收(和显示)字符串中的字符的。这看起来像: document.getElementById("outDiv").innerHTML += myNextChar; 在一行上显示100个字符,然后开始新行,直到所有字符都显示出来为止 <html> <head> <title>Exercise</tit

当我点击按钮时,它不会运行

添加一个id为btnPrint、值为“Print”的按钮和一个名为printString()的事件处理程序

添加用于增量接收(和显示)字符串中的字符的。这看起来像:

document.getElementById("outDiv").innerHTML += myNextChar;
在一行上显示100个字符,然后开始新行,直到所有字符都显示出来为止

<html>
<head>
    <title>Exercise</title>
    <script language="JavaScript" type="text/JavaScript">
    function printString(){
        str="The nefarious thing about performance bugs is that the user may never know they are there - the program appears to work correctly, carrying out the correct operations, showing the right thing on the screen or printing the right text. It just does it a bit more slowly than it should have. It takes an experienced programmer, with a reasonably accurate mental model of the problem and the correct solution, to know how fast the operation should have been performed, and hence if the program is running slower than it should be";
        var myNextChar="";
        var char=0;
        function innerLoop(){
            myNextChar=str.slice(char,char+1);
            if((char+1)%100===0){
                myNextChar+="<br />"
            }
            char++;

            document.getElementById("str").innerHTML += myNextChar;

            setTimeout(innerLoop,10);
            }
        innerLoop();

        }
        //window.onload  = printString;
    </script>
</head>
<body>

<button onclick="printString()">Print</button>
</body>

在关闭
标记并添加id为str的div之前,需要将脚本移动到

<div id='str'></div>

函数printString(){
str="关于性能缺陷的邪恶之处在于,用户可能永远不会知道它们在那里——程序似乎工作正常,执行正确的操作,在屏幕上显示正确的内容或打印正确的文本。它只是比它应该有的速度慢了一点。这需要有经验的程序员,具有合理的准确性问题的心智模型和正确的解决方案,以了解操作应以多快的速度执行,从而了解程序运行是否比应以的速度慢”;
var myNextChar=“”;
var-char=0;
函数innerLoop(){
myNextChar=str.slice(char,char+1);
如果((字符+1)%100==0){
myNextChar+=“
” } char++; document.getElementById(“str”).innerHTML+=myNextChar; var id=设置超时(内部循环,10); if(char>str.length)clearTimeout(id); } innerLoop(); } //window.onload=printString;

运动
打印

您的HTML不包含ID为“str”的元素。str=“性能方面的邪恶之处在于JavaScript中的变量“str”,而不是ID为“str”的HTML中的元素。完全不同的东西。对不起,我刚刚开始学习这门语言,我应该添加什么来解决这个无元素问题?只需将
添加到HTML中就可以修复错误。不仅在主体标记关闭之前移动脚本标记没有效果,它与当前放置脚本标记的最佳实践背道而驰。OPs代码的主要问题是缺少元素。我想投赞成票,这解决了我的问题,谢谢,我该如何将打印按钮放在打印的顶部I更新的显示答案打印按钮放在打印新问题的顶部,当我单击打印,它工作正常,但如果您等待它完成,您可以看到它仍然像打印一样空白,并且按钮一直向下。谢谢,但是当按钮移动到顶部时,“向下移动”将不会显示
<div id='str'></div>