【问题标题】:Javascript included the word undefined as part of the outuptJavascript 包含单词 undefined 作为输出的一部分
【发布时间】:2021-12-31 01:42:00
【问题描述】:
    var i = 0;
    var txt = 'Christmas Family Service - Sunday 19th December at 11:45 am.  Come along to Bethany Evangelical Church and find out about the real meaning of Christmas.'; /* The text */
    var speed = 50; /* The speed/duration of the effect in milliseconds */
    
    function typeWriter() {
      if (i < txt.length) {
        document.getElementById("demo").innerHTML += txt.charAt(i);
        i++;
        setTimeout(typeWriter, speed);
      }
    }


<div class="announce">

<p id="demo">
<script>

document.write(typeWriter());
</script>

</p>

</div>

Cundefined 圣诞节家庭服务 - 12 月 19 日星期日上午 11:45。一起来伯大尼福音教会,了解圣诞节的真正意义。

【问题讨论】:

  • 当您执行document.write 时,它会将参数添加到文档中。在您的情况下,typeWriter() 的结果是undefined(因为typeWriter 不返回任何内容)

标签: javascript html output undefined


【解决方案1】:

你的

<p id="demo">
  <script>
    document.write(typeWriter());
  </script>
</p>

将调用 typeWriter 的返回值插入到该 #demo 元素中 - 但该函数不返回任何内容。

反正有no real good reason 可以使用document.write。您需要做的就是调用函数,而不是使用document.write。

var i = 0;
var txt = 'Christmas Family Service - Sunday 19th December at 11:45 am.  Come along to Bethany Evangelical Church and find out about the real meaning of Christmas.'; /* The text */
var speed = 50; /* The speed/duration of the effect in milliseconds */

function typeWriter() {
  if (i < txt.length) {
    document.getElementById("demo").innerHTML += txt.charAt(i);
    i++;
    setTimeout(typeWriter, speed);
  }
}

typeWriter();
<div class="announce">
  <p id="demo"></p>
</div>

修复代码的其他部分:

  • 您只需要选择一次元素,而不是每次循环运行时
  • .innerHTML 仅应在有意插入 HTML 标记时使用 - 对于纯文本,.textContent 更快、更安全且更可预测

let i = 0;
const txt = 'Christmas Family Service - Sunday 19th December at 11:45 am.  Come along to Bethany Evangelical Church and find out about the real meaning of Christmas.'; /* The text */
const speed = 50; /* The speed/duration of the effect in milliseconds */

const demo = document.getElementById("demo");
function typeWriter() {
  if (i < txt.length) {
    demo.textContent += txt[i];
    i++;
    setTimeout(typeWriter, speed);
  }
}

typeWriter();
<div class="announce">
  <p id="demo"></p>
</div>

【讨论】:

  • 在函数外部缓存元素也是一个好主意,并使用textContent而不是innerHTML。
  • 感谢您对此 javascript 的快速帮助。如果我从 sn-p 剪切并粘贴代码,我的 html 上没有输出。我已经引用了javascript:
  • @Gvee 确保在#demo 元素之后 插入脚本,或使用defer 标记。如果这不是问题,请检查您的浏览器控制台是否有错误(一如既往)
  • defer 标签效果很好。感谢您的帮助。
猜你喜欢
  • 2016-10-07
  • 1970-01-01
  • 2016-12-21
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-29
  • 2017-12-07
相关资源
最近更新 更多