【发布时间】:2020-11-03 04:06:59
【问题描述】:
我想动态地将点击事件添加到创建的元素中,当用户点击按钮时创建一些元素(在下面的代码中显示的元素)和当用户点击名为remov的元素时必须运行名为deltion的函数但是不起作用。我该如何实现?
我使用 Vue js
methods: {
showinfo: function() {
db.collection("Studnets")
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
const student = document.createElement("tr");
const email = document.createElement("td");
email.innerText = doc.data().email;
const name = document.createElement("td");
name.innerText = doc.data().name;
const phone = document.createElement("td");
phone.innerText = doc.data().phone;
const stage = document.createElement("td");
stage.innerText = doc.data().stage;
const remov = document.createElement("button");
const pic = document.createElement("img");
pic.setAttribute("src","/dist/delete.svg?afdf9975229cdc15458e851b478bb6cb");
remov.classList.add("del");
//the problem
remov.addEventListener("click", this.deltion());
student.appendChild(email);
student.appendChild(name);
student.appendChild(phone);
student.appendChild(stage);
student.appendChild(remov);
remov.appendChild(pic);
document.getElementById("studentList").appendChild(student);
},
deltion: function(e) {
const rawStudent = e.target;
const raw = rawStudent.parentElement;
console.log(raw);
raw.remove();
}
【问题讨论】:
-
如果使用Vue.js,应该不需要直接操作Dom。
-
您使用的是 Vue,但您的整个方法是 vanilla JS 方式。使用 vue,您可以向应用程序状态添加一个新数据行,这会导致重新渲染,由于模板中的循环,它会显示一个带有额外行的表格。除非确实需要,否则您永远不会直接操作 DOM。 Vue list rendering
-
对于初学者来说,
remov.addEventListener("click", this.deltion());将是remov.addEventListener("click", this.deltion);或remov.addEventListener('click', e=>{ this.deltion(e); });或者你不会得到EventObject... 但我真的不喜欢你的编码风格。提高你的技能。
标签: javascript vue.js dom vuejs2 createelement