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;
}
- 可以"get"或"set"property
- 可以"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
.innerHTML 把輸入放進語法當中
document.querySelector("h1").innerHTML = "<em>BYE</em>"
=> BYE.textContent 把輸入當成純字串
document.querySelector("h1").textContent = "<em>BYE</em>"
=> < em> BYE </em >
更改物件的Attribute
呼叫物件的所有attriute
document.querySelector("a").attributes;
NamedNodeMap {0: href, href: href, length: 1}取得物件的attribute內容
document.querySelector("a").getAttribute("href");
'https://www.google.com'修改物件的attribute內容
document.querySelector("a").setAttribute("href", "https://www.bing.com");