即使被调用,函数也不会触发

时间:2019-08-24 23:08:44

标签: javascript

我正在写一个网站,其中的一部分需要一些文本来显示,就像正在键入一样。但是,即使被调用,我执行此操作的功能之一(typewriter2也不起作用。

我尝试遍历代码,并分别对其进行测试。代码运行正常,但是typewriter2函数不会启动。

var x = document.getElementById("businesscard");
if (x.style.display === "none") {
  x.style.display = "block";
} else {
  x.style.display = "none";
}
var i = 0;
var txt1 = "cd Info && cat Business Card";
var speed = 75;

function typeWriter() {
  if (i < txt1.length) {
    document.getElementById("cmd1").innerHTML += txt1.charAt(i);
    i++;
    setTimeout(typeWriter, speed);
  } else {
    BusinessCard();
    
  }
}
function BusinessCard() {
  var x = document.getElementById("businesscard");
  if (x.style.display === "none") {
    x.style.display = "block";
    typeWriter2();
  } else {
    x.style.display = "none";
  }
}

var txt = "cat Websites";

function typeWriter2() {
  if (i < txt.length) {
    document.getElementById("cmd2").innerHTML += txt.charAt(i);
    i++;
    setTimeout(typeWriter2, speed);
  }
}
/* unvisited link */
a:link {
  color: white;
}

/* visited link */
a:visited {
  color: white;
}

/* mouse over link */
a:hover {
  color: blue;
}

/* selected link */
a:active {
  color: blue;
}


body {
  background-color: #300A24;
  color: white;


    font-family: 'Ubuntu Mono', monospace;


}
<body onload="typeWriter()">

<link href="https://fonts.googleapis.com/css?family=Ubuntu+Mono&display=swap" rel="stylesheet">

  <p id="cmd1">[dmeskin@code-u.org ~]$ </p>
  <div id="businesscard"><p>Daniel Notmylastname<br> Student at notmyschoool<br> Systems Administrator<br>
    <a href="http://code-u.org">http://code-u.org</a><br>
    <a href="mailto:1byte@gmail.com">1byte@gmail.com</a><br>
    <a href="tel:9175556761">+1(917)-555-6761</a><br><p id="cmd2">[dmeskin@code-u.org Info]$ </p>

应该发生的是,typeWriter2()在未隐藏businesscard之后开始,但是没有。

2 个答案:

答案 0 :(得分:2)

使用全局变量会伤害您。这样会使代码变得难以预测,特别是如果您在多个函数中使用相同的变量。

另一件事:不要在每次需要元素时都向DOM查询元素:查询DOM非常昂贵,应尽可能避免(在您的代码中没关系,但是由于修复很容易,我希望您从一开始就学习做正确的事情。)在您的代码中,它是75毫秒前的元素。

另一件事:不要重复自己。如果您在同一程序中一遍又一遍地编写同一段代码,或者仅使用另一个变量,则该将其移至函数了。然后,在进行故障排除时,您也可以只关注一个地方,如果需要的话,也可以使用一个地方来应用修复程序。

以下示例无论如何都不是完美的。一个现代的变体可能会使用arrow-functions,但在此示例中我决定反对,因为如果您不习惯它们,可能很难阅读。

这是一个经过改进的版本,为打字机效果重复使用了相同的功能。

// A function that hides and show the Business card depending on the given variable.
function setBusinessCardVisible (visibility) {
  const elem = document.getElementById("businesscard");
  elem.style.display = visibility ? 'block' : 'none';
}

// A generig typewriter that takes an object and callback as arguments.
// The arg object has:
//   elem : the element that text shold be appended to
//   cmd : The text that should be added
//   delay : the delay between characters
function typeWriter (arg, callback) {
  let index = 0; // set the index for this typewriter to 0.

  // Get the elment ONE time, and resuse that.
  arg.elem.textContent = arg.prompt;

  const length = arg.cmd.length;
  // Using setInteval to start ONE timer that will be called
  // until it is cleared with clearInterval
  let timer = setInterval(
    function () {
      // Add the character
      arg.elem.textContent += arg.cmd.charAt(index);
      // increment index and see if we are finished
      if (index++ >= length) {
        clearInterval(timer); // stop the timer
        if (callback) callback(); // call callback if specified
      }
    },
    arg.delay
  );
}

// call this function to start the effect
function startTyping () {
  const
    elem1 = document.getElementById('cmd1'),
    elem2 = document.getElementById('cmd2'),
    delay = 75, // Set the delay here and reuse it below
    cmdprompt1 = "[dmeskin@code-u.org ~]$ ", // Part one: hide the card.
    cmdprompt2 = "[dmeskin@code-u.org Info]$ ";
  elem1.textContent = cmdprompt1;
  elem2.textContent = cmdprompt2;
  // Part one: hide the card.
  setBusinessCardVisible(false); // Start the first typewriter
  typeWriter({
    elem: elem1,
    prompt: cmdprompt1,
    cmd: "cd Info && cat Business Card",
    delay: delay
  }, function () { // part two, show the card
    setBusinessCardVisible(true); // Start the secord typewriter
    setTimeout( function() {
      typeWriter({
        elem: elem2,
        prompt: cmdprompt2,
        cmd: "cat Websites",
        delay: delay
      }, function () {
        setTimeout(function () {
          setBusinessCardVisible(false);
          elem1.textContent = cmdprompt1;
          elem2.textContent = cmdprompt2;
          setTimeout(startTyping, 2000); // Restart after 2 seconds
        }, 2000);
      })
    }, 2000) // delay after showing card
  });
}
a,
a:link,
a:visited,
a:hover,
a:active {
  color: blue;
}

body {
  background-color: #300A24;
  color: white;
  font-family:  monospace;
}
<body onload="startTyping()">
  <p id="cmd1">[dmeskin@code-u.org ~]$ </p>
  <div id="businesscard">
    <p>Daniel Notmylastname<br> Student at notmyschoool<br> Systems Administrator<br>
    <a href="http://code-u.org">http://code-u.org</a><br>
    <a href="mailto:1byte@gmail.com">1byte@gmail.com</a><br>
    <a href="tel:9175556761">+1(917)-555-6761</a><br>
    <p id="cmd2">[dmeskin@code-u.org Info]$ </p>
  </div>
</body>

答案 1 :(得分:0)

问题在于i未设置为正确的值,必须重命名。