動態產生水果清單
//HTML <ul class="fruitList"></ul>
const fruits = ['蘋果', '香蕉', '橘子', '西瓜'];
const list = document.querySelector('.fruitList');
function renderFruits() {
let html = ''; // 先準備一個空字串,用來慢慢「疊加」HTML內容
for (let i = 0; i < fruits.length; i++) {
html += '<li>' + fruits[i] + '</li>';
}
list.innerHTML = html; // 迴圈跑完後,一次性塞進去
}
renderFruits();
寫入網頁裡
重點觀念
為什麼要先組字串,最後才塞進 innerHTML?
想像你在包便當:如果你每加一樣菜就把便當蓋打開又蓋上(相當於每次迴圈都直接操作 innerHTML),會很沒效率。比較好的做法是先把所有菜都放到一個托盤上(字串變數 html),最後一次裝進便當盒(list.innerHTML = html)。
createElement 就像「訂做一個新家具」,做好之後還要「搬進房間」(用 appendChild)才會顯示出來
HTML <div class="box"></div>
const box = document.querySelector('.box');
// 步驟1:建立元素(還沒顯示在畫面上,只是存在記憶體裡)
const newPara = document.createElement('p');
// 步驟2:給它內容
newPara.textContent = '哈囉,我是新段落!';
newPara.setAttribute('style', 'color: blue;');
// 步驟3:放進畫面裡(不放的話畫面不會出現任何東西)
box.appendChild(newPara);
網頁顯示
哈囉,我是新段落!(藍字)
假設要把一個陣列的資料,逐一變成清單項目
HTML <ul class="fruitList"></ul>
const fruits = ['蘋果', '香蕉', '橘子', '西瓜'];
const list = document.querySelector('.fruitList');
function renderFruits() {
for (let i = 0; i < fruits.length; i++) {
const li = document.createElement('li'); // 訂做一個新的 <li>
li.textContent = fruits[i]; // 填內容
list.appendChild(li); // 搬進 <ul> 裡
}
}
renderFruits();
寫入網頁裡
假設要幫每個項目加上 class,還要能點擊
HTML <ul class="fruitList"></ul>
const fruits = ['蘋果', '香蕉', '橘子'];
const list = document.querySelector('.fruitList');
function handleClick() {
console.log('你點了:', this.textContent);
}
function renderFruits() {
for (let i = 0; i < fruits.length; i++) {
const li = document.createElement('li');
li.textContent = fruits[i];
li.classList.add('fruit-item'); // 加上 class,方便套樣式
li.addEventListener('click', handleClick); // 加上點擊事件
list.appendChild(li);
}
}
renderFruits();
點擊「香蕉」時,console 會印出:你點了: 香蕉
| .. | createElement + appendChild | innerHTML |
|---|---|---|
| 效能 | 較好,尤其資料量大時 | 資料量大時較差 |
| 能否加事件監聽 | 可以直接在建立時就加上 | 需要建立完後,重新選取才能加事件 |
| 寫法 | 稍微囉唆一點 | 簡潔,但字串拼接容易出錯 |
| 適合情境 | 需要精細控制(事件、屬性)時 | 單純顯示文字內容時 |
生活化比喻:
innerHTML 像是「把一張寫好的清單直接貼在牆上」,快但沒辦法個別互動;createElement 則像「一個一個做出實體公告牌,還可以在上面裝按鈕讓人互動」,比較費工但功能更完整