HTML元素仅在输入输入提示后显示

时间:2017-09-29 04:05:36

标签: javascript html dom

我正在编写非常简单的JavaScript代码,通过在提示符中输入新标题来替换h1标题。我不明白为什么原始标题在首次加载页面时没有显示。只有在我向提示输入新标题后,标题才会显示。我已经将脚本标记放在正文的末尾。我做错了什么?我确实得到了原来的标题" Hello World"登录控制台。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Playing with the DOM</title>
  </head>
  <body>
    <div>
      <h1 id="main-heading">Hello World</h1> 
    </div>
    <script>
      var headingElement = document.getElementById('main-heading');
      console.log(headingElement.innerHTML);
      var newHeadingText = prompt('Please provide a new heading');
      headingElement.innerHTML = newHeadingText;
    </script>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

它有点hacky方式并且不是每次都有效(看起来像是Chrome功能),但你可以添加DOMContentLoaded监听器和空setTimeout,它会让在脚本执行之前要完全加载的DOM:

&#13;
&#13;
document.addEventListener('DOMContentLoaded', function() {
  setTimeout(function() {
    var headingElement = document.getElementById('main-heading');
    var newHeadingText = prompt('Please provide a new heading');
    headingElement.innerHTML = newHeadingText;
  })
});
&#13;
<div>
  <h1 id="main-heading">Hello World</h1> 
</div>
&#13;
&#13;
&#13;

jQuery document.ready的示例:

&#13;
&#13;
$(document).ready(function() {
  setTimeout(function() {
    var headingElement = document.getElementById('main-heading');
    var newHeadingText = prompt('Please provide a new heading');
    headingElement.innerHTML = newHeadingText;
  })
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <h1 id="main-heading">Hello World</h1> 
</div>
&#13;
&#13;
&#13;