interview-answe icon indicating copy to clipboard operation
interview-answe copied to clipboard

178.怎样向页面添加 JavaScript?

Open webVueBlog opened this issue 4 years ago • 1 comments

[js]

webVueBlog avatar Apr 15 '20 06:04 webVueBlog


内部 JavaScript
document.addEventListener("DOMContentLoaded", function() {
  function createParagraph() {
    let para = document.createElement('p');
    para.textContent = '你点击了这个按钮!';
    document.body.appendChild(para);
  }

  const buttons = document.querySelectorAll('button');

  for(let i = 0; i < buttons.length ; i++) {
    buttons[i].addEventListener('click', createParagraph);
  }
});

<script src="script.js" async></script>

function createParagraph() {
  const para = document.createElement('p');
  para.textContent = '你点击了这个按钮!';
  document.body.appendChild(para);
}
<button onclick="createParagraph()">点我呀</button>

要让脚本调用的时机符合预期,需要解决一系列的问题。这里看似简单,实际大有文章。最常见的问题就是:HTML 元素是按其在页面中出现的次序调用的,如果用 JavaScript 来管理页面上的元素(更精确的说法是使用 文档对象模型 DOM),若 JavaScript 加载于欲操作的 HTML 元素之前,则代码将出错。

document.addEventListener("DOMContentLoaded", function() {
  . . .
});

这是一个事件监听器,它监听浏览器的 "DOMContentLoaded" 事件,即 HTML 文档体加载、解释完毕事件。事件触发时将调用 " . . ." 处的代码,从而避免了错误发生

webVueBlog avatar Apr 15 '20 06:04 webVueBlog