如何阻止我的 HTML 中的示例代码/文本被识别为代码/激活



我目前正在研究一个hackertyper,我的假代码(你"输入"的脚本目前正在被读取为真实代码,从而搞砸了我的程序。我在假代码/脚本中也有需要触发的命令,即 br,因为如果它们不会触发,当有人使用 hackertyper 时,整个程序将写在一行上。

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

// pre defined variables
let num;
let counter;
counter = true;
num =0;
// this shows which text will go on the screen
let text = String("//right here is the problem. code that's put inside these brackets will be recognized as "real code" and at the same time <br>(or €)'s need to be recognized 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();
}
}

您的代码存在一些问题:

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

我修复了下面的截图中的一些问题。希望这有帮助。

// 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>

请确保在键入文本之前单击代码段窗口,否则它将不起作用。

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

最新更新