頁面上元素眾多,為了方便操作,我們會替它們掛上「身分證」。最常見的三個屬性是 name、id 與 class,用途其實涇渭分明。
格式:<input type="text" name="username" />
主要用在三個地方:
username='輸入的值'。<input type="radio" name="sex"/>男 <input type="radio" name="sex"/>女
function changtxtcolor() {
var txts = document.getElementsByName('txtcolor');
for (var i = 0; i < txts.length; i++) {
txts[i].style.backgroundColor = 'red';
}
}
特性:name 在同一頁面中不必唯一。
格式:<input type="password" id="userpwd" />
用途:
document.getElementById(id) 精準取得元素。<label for="userid">用戶名:</label>特性:id 在同一頁面中必須唯一,重複會讓 JS 與 CSS 的行為變得不可預期。
格式:<input type="button" class="btnsubmit" />
主要搭配 CSS 使用,把共用樣式收攏到一個類別,需要的元素掛上即可。一個 class 屬性可以放多個類名,但必須用空格隔開:
<input type="button" class="btnsubmit btnopen" />
一句話總結:name 給伺服器看、id 給 JS 精準定位、class 給 CSS 大量套用。