JavaScript 第六章总结: Getting to know the DOM

前言

这一章节介绍 DOM, 
使用 DOM 的目的是使的网页能够变得 dynamic,使得 pages that react, that respond, that update themselves after they've been loaded.

什么是 DOM ?

结构:


以 document 开始,接下来是 这个element,接下来是 和 这两个 element,不断内嵌深入。

定义:

When you load a page into the browser, ont only does the browser parse the HTML and then render it to the display, it also creates a set of objects that represent your mark up. These objects are stored in DOM.

简而言之, DOM 是 a set of objects to represent mark-ups

DOM 是 HTML 与 JavaScipt 的共同之处

JavaScript and HTML are two different things. HTML is markup and JavaScript is code.但是它们有一个共同之处,那就是DOM. 通过它,两者可以进行相互的交流

使用 DOM

步骤

  1. LABLE: 在 HTML 中 lable 一个 element 的 id:<p id:greenplanet></p>
  2. CREATE:在 JavaScript 中创建一个 element object,需要使用到document 这个 global object 和它的 getElementById: var planet = document.getElementById("greenplanet")
  3. MODIFY:使用刚刚创建的 object 的方法:innerHTML, 来修改其内容:
  4. MODIFYL:还可以用 document object 的 getAttibute 和 setAttribute 两种方法来设置 element object 的属性,格式为:setAttribute("nameOfAttribute","valueOfAttribute")

其他知识:

  • CREATE 相关: document 这个 object 属于 built-in object, 并且它含有很多附带的 attribute 和 method,可以调用。
  • CREATE 相关:除了 getElementById() 这种方法来确定有 id 属性的 element,还可以使用 getElementbyClassName() 来确定有 class 属性的 element.
  • MODIFY 相关:innerHTML 指的是不包括两边 tags 的 HTML,此外还有 outerHTML 是包括 tags 的 HTML.
  • MODIFY相关:不仅仅可以 get element from the DOM,还可以 Create and add elements to the DOM, Remove elements from the DOM, Traverse the elements in the DOM.

解决 geyElementById 返回值为 null 的问题

问题原因

由于代码从上往下运行,在调用document.getElement() 的时候,并没有显示处所要的 id ,所以返回值为 null.

解决办法

格式:

使用 window 这个 bullt-in object 的一个叫做 onload的 property,它的作用是 get called after the page has loaded.
其中 window 这个 object 本质上 represent the broswer window.

范例:

<script>
function init() {
    var planet = document.getElementById("greemplanet");
    planet.innerHTML = "Red Alert: hit by phaser fire!";
    }
    
window.onload = init;
</script>

关于 onload 这个 property

格式:为 onload assign 一个函数
范例:window.onload = init;
(注意不要加括号,因为不是使用函数值,而是调用函数)
详细内容:
onload,属于 callback,或者 event handler
,它先给一个 object 一个 function ,然后当object 执行到某一个时刻之时,再进行调用这个 function.
作者是这样写的:

A callback works like this: give a function to the object that knows about the event. When the event occurs, that object will call you back, or notify you, by calling that function

onload 这个时刻代表了 as soon as the page is fully loaded.

并且这里还有其他的 event 用于 JavaScript 中的 event handler 来处理





原文地址:https://www.cnblogs.com/FBsharl/p/10222476.html