易,哟,所以我想做的就是按下按钮" id"触发事件lisener后的函数内部,如果有意义的话。但由于它是一个固定的功能,我无法获得按钮" id"通过"这个"句法。 deleteMemberCallback(方法)函数是一个" set"函数,假设回调" id"一排桌子。但要获得" id"我需要知道按下哪个按钮的行。如果deleteMemberCallback函数没有设置语法,我可以很容易地得到按钮" id"通过调用" this.id",这是不可能的sems ...如果有人有任何聪明的想法,我会很高兴听到他们;)
class UIHandler {
constructor() {
this.UIElement = createTable();
}
addMember(member){
console.log("Person added!");
let rowEl = this.UIElement.insertRow();
rowEl.id = member.id;
rowEl.insertCell().textContent = member.firstname;
rowEl.insertCell().textContent = member.lastname;
rowEl.insertCell().textContent = member.address;
rowEl.insertCell().textContent = member.phone;
//Adds delete button to row
let btnDel = document.createElement("button");
let delText = document.createTextNode("Delete");
btnDel.appendChild(delText);
btnDel.id = "b" + member.id;
rowEl.insertCell().appendChild(btnDel);
btnDel.addEventListener('click', this.deleteMemberCallback, false);
//Adds edit button to row
let btnEdit = document.createElement("button");
let editText = document.createTextNode("Edit");
btnEdit.appendChild(editText);
rowEl.insertCell().appendChild(btnEdit);
}
set deleteMemberCallback(method) {
method(this.id);
}
}
class AppController {
constructor(memberlist, addMember) {
this.memberlist = memberlist
this.addMember = addMember
}
run() {
this.ui = new UIHandler()
document.getElementById(this.memberlist).appendChild(this.ui.UIElement)
/*
* Code added temporarily to test that deleteMember works as intended.
*/
this.ui.addMember({"id":1,"firstname":"Ole","lastname":"Olsen","address":"Olsenbakken","phone":"91826453"})
this.ui.addMember({"id":2,"firstname":"Per","lastname":"Persen","address":"Persenbakken 77","phone":"14546567"})
this.ui.deleteMemberCallback = (id) => {
const doDelete = window.confirm(`Do you really want to delete member with id ${id}?`)
if (doDelete) {
window.alert(`Member ${id} should be deleted.`)
} else {
window.alert(`Member ${id} should not be deleted.`)
}
}
}
}
编辑: 我试过了:
btnDel.addEventListener('click', this.deleteMemberCallback.bind(btnDel), false);
btnDel.addEventListener('click', this.deleteMemberCallback.bind(this), false);
都失败了 - > "无法阅读财产' bind'未定义"
EDIT2: 好的,所以我有点想念这个练习。但无论如何,我得到了帮助,并得到了这个解决方案。所以我刚刚删除了eventlistener形式的按钮,这些按钮不再用了......
set deleteMemberCallback(method) {
let buttons = document.getElementsByTagName("button");
for(let i = 0; i < buttons.length-1; i++) {
buttons[i].onclick = function(e) {
let tmp = buttons[i].parentNode.parentNode.id;
method(tmp);
}
}
}