问题描述
我在页面上创建了各种元素,需要将mousedown事件附加到每个元素上。将为类中的每个元素执行不同的操作。我有:
const myParent = document.getElementById("myParent")
var myNewElement = document.createElement("div");
myNewElement.setAttribute("class","myClass");
myNewElement.setAttribute("id","myId");
myParent.appendChild(myNewElement);
document.addEventListener("mousedown",function(event) {
if (event.target.id == "myId") {
console.log("click: myId")
// do stuff when myNewElement is clicked.
} else if (event.target.id == "someOtherId") {
console.log("click: someOtherId")
// do something else when some other element is mousedown
}
});
#myParent { padding: 20px 40px; background: #ccc; }
#myId { width: 20px; height: 20px; background: red; }
<div id="myParent">
</div>
<button id="someOtherId">Click me</button>
不幸的是,我无法通过以下方式引用“ myNewElement”:
event.target.id ==“ myId”
我如何进行这项工作?另外,是否可以通过简单地使用我为其分配的变量名称myNewElement来引用“ myNewElement”?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)