JavaScript 語法架構 & DOM & OOP


Posted by pei_______ on 2022-05-27

JavaScipt的語法位置

inline

<body onload="alert('Hello');">

internal

<body>
    <script type="text/javascript">
        alert("Hello");
    </script>
</body>

external

// index.html
<body>
    <script src="" charset="utf-8"></script>
</body>

// index.js
alert("Hello");



Document Object Model 文件物件模型

依照child位置尋找物件

document.firstElementChild;
document.lastElementChild;

依照物件的Tag Name / Class Name / Selector尋找"所有"符合之物件

  • 無論符合的物件數量為何,皆以陣列方式回傳
items_array = document.getElementsByTagName("li");
items_array = document.getElementsByClassName("btn");
items_array = document.querySelectorAll("1i");

依照物件的陣列位置 / Id / Selector尋找"唯一"符合之物件

item = items_array[2];
item = document.getElementById("list");

// 以下是回傳"第一個"符合條件之物件
tem = document.querySelector("1i a");
item = document.querySelector("li.item");



類別class & 物件 Object

Construct Function & new object

/* ------- Use Construct Function to set objects ------ */

function BellBoy (name, age, languages){
    this.name = name;
    this.age = age;
    this.languages = languages;
    this.moveSuitcase = function() {
        alert("May I help you?");
    }
}

var bellBot1 = new BellBoy("Timmy", 19, "English");


/* ---------- Just set an object --------- */

const bellBoy = {
    name = name;
    age = age;
}

  1. 可以"get"或"set"property
  2. 可以"call"method
ex. buttonn

property
.innerHTML
.textContent
.style
.firstChild

buttonn.style.color = "red";
num_of_item_in_array = items_array.length;


method
.click()
.appendChild()
.setAttribute()

大部分"樣式"的設計會在CSS裡,而JS用來調整class的開關

ex.
// styles.css的設計
.huge {
    font-size: 10rem;
}

// JS的設計執行
document.querySelector("h1").classList.add("huge");
document.querySelector("h1").classList.toggle("huge");

物件的文字設定 .innerHTML vs. .textContent

  1. .innerHTML 把輸入放進語法當中
    document.querySelector("h1").innerHTML = "<em>BYE</em>"
    => BYE

  2. .textContent 把輸入當成純字串
    document.querySelector("h1").textContent = "<em>BYE</em>"
    => < em> BYE </em >


更改物件的Attribute

  1. 呼叫物件的所有attriute
    document.querySelector("a").attributes;
    NamedNodeMap {0: href, href: href, length: 1}

  2. 取得物件的attribute內容
    document.querySelector("a").getAttribute("href");
    'https://www.google.com'

  3. 修改物件的attribute內容
    document.querySelector("a").setAttribute("href", "https://www.bing.com");


#javascript #web系列







Related Posts

[ week 6 ] Chrome DevTools 除錯筆記

[ week 6 ] Chrome DevTools 除錯筆記

學習資源分享

學習資源分享

How to Request an AWS SSL/TLS Certificate

How to Request an AWS SSL/TLS Certificate


Comments