Skip to content

178.怎样向页面添加 JavaScript? #178

Open
@webVueBlog

Description

@webVueBlog
Member

[js]

Activity

webVueBlog

webVueBlog commented on Apr 15, 2020

@webVueBlog
MemberAuthor
内部 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 文档体加载、解释完毕事件。事件触发时将调用 " . . ." 处的代码,从而避免了错误发生

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @webVueBlog

        Issue actions

          178.怎样向页面添加 JavaScript? · Issue #178 · weekCodeing/interview-answe