1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
const component = {
data:[ "蘋果","香蕉","鳳梨" ],
showData(){
let list = document.querySelector(".list");
let str = "";
this.data.forEach((item,id) => {
str += `<li>${item}
<button type="button" class="btn" data-num="${id}">刪除</button>
</li>`
})
list.innerHTML = str;
let btns = document.querySelectorAll(".btn");
btns.forEach((item)=>{
//使用箭頭函數可以,讓this指向外層
item.addEventListener("click",(event)=>{
this.removeData(event.target.dataset.num);
})
})
},
removeData(id){
this.data.splice(id, 1);
this.showData();
},
initData(){
this.showData();
}
}
component.initData();
|