AP102 2016/4/27 JavaScript querySelectorAll('')

AP102 2016/4/27 JavaScript querySelectorAll('')
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <link rel="stylesheet" href="">
        <script src="30_new.js"></script>
        <title>Query Selector All</title>
    </head>
    <body>
        <div>
            <p>First</p>
            <p>Second</p>
            <p>Third</p>
            <p>Fourth</p>
        </div>
    </body>
</html>

一開始我們先宣告一個函式
dofirst
然後建立一個陣列的資料型態
對p這個html標籤

在w3c school裡面的定義querySelectorAll(”)是

Definition and Usage
The querySelectorAll() method returns all elements in the document that matches a specified CSS selector(s), as a static NodeList object.

The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

Tip: You can use the length property of the NodeList object to determine the number of elements that matches the specified selector, then you can loop through all elements and extract the info you want.

像這樣的範例
例如var x = document.querySelectorAll(“.example”);

然後這時候直接把x替換成list這種陣列的資料型態
然後將[i]陣列內的元素全部取出
當你點擊每一個list節點,p標籤的所有節點被點擊
都會執行talk這個事件

function doFirst(){
    //先與畫面產生關聯,再建事件聆聽的功能
    var list = document.querySelectorAll('p');
    //list是陣列的資料型態

    for(var i=0; i<list.length; i++){
        list[i].onclick = talk;
    }   
}

function talk(){
    alert('hi~~');
}

window.addEventListener('load',doFirst,false);
//window.onload=doFirst;

Comments

Popular posts from this blog

MEGA 暫存檔案刪除

IOS GCD多執行緒

利用CMD指令強制刪除