如何在我的html中停止示例代码/文本被识别为代码/激活

问题描述 投票:1回答:2

我正在制作一个hackertyper,我的假代码(你“输出”的脚本目前正在被读作真实的代码,因此弄乱了我的程序。我还在需要触发的假代码/脚本中有命令是的,因为如果他们不会触发,当有人使用hackertyper时,整个程序将写在一行。

是否有一个命令,让我排除脚本代码,但为功能留出空间(我想使用€符号作为br的函数),以便我的程序将停止崩溃?对此的解决方案可能很明显,但我似乎无法找到它,提前感谢!

// pre defined variables
let num;
let counter;
counter = true;
num =0;

// this shows wich text will go on the screen
let text = String("//right here is the problem. code that's put inside these brackets will be recognised as "real code" and at the same time <br>(or €)'s need to be recognised also// ");
// splits the text into an array after every character
let result = text.split("");

// start of the hackertyper
function keyPress(){
    music();
    document.onkeypress = function() {
        // where text will be shown
        num++;
        document.write(result[num]);
        // a loop
        keyPress();
    }
}
javascript html
2个回答
0
投票

在文本字符串中将"real code"更改为\"real code\"


1
投票

您的代码存在一些问题:

  • 您应该避免使用document.write,因为它会删除您的原始文档。这就是你必须在onkeypress函数中重置keyPress事件处理程序的原因。相反,您应该将文本打印到HTML元素中。
  • 你没有限制地循环。 num递增,并且在某些时候,将高于你的result数组的长度。您需要修复它,否则您将打印“undefinedundefinedundefined”...
  • 您应该避免使用String()构造函数。由于几个原因,最好的一个是用它构造的字符串是键入的“对象”,这可能是有害的。
  • 如果您在该字符串中编写代码,请确保转义双引号或使用单引号括起您的字符串。在您提供的示例中,您没有转义双引号,这导致语法错误。

我在下面的snipplet中解决了一些问题。希望这可以帮助。

// pre defined variables
let num = 0;
let counter = true;

// this shows wich text will go on the screen
let text = "let name = 'John';\nlet firstName = 'Jack'\n;";
// splits the text into an array after every character
 let result = text.split("");

// start of the hackertyper
function keyPress(){

// where text will be shown
 if (num < result.length) {
   document.getElementById("codeType").innerHTML += result[num];
   num++;
 }
 

}

document.addEventListener('keypress', keyPress);
<span id="codeType"></span>

确保在键入文本之前单击片段窗口,否则它将无法工作。

© www.soinside.com 2019 - 2024. All rights reserved.