我试图在javascript中添加多个事件监听器UL
。
如果已经点击了我的.preventDefault()
元素之一,如何为.card
创建条件?
const cd = document.getElementById('listDeck')
cd.addEventListener('click', flipFirst, false)
function flipFirst(e) {
if (e.target && e.target.nodeName == "LI") {
var firstMove = document.getElementById(e.target.id)
firstMove.classList.add('open', 'show')
console.log('first card was clicked')
e.currentTarget.removeEventListener('click', flipFirst);
}
}
cd.addEventListener('click', function(evt) {
if () {
//condition is true
//then prevent default
}
var secondMove = document.getElementById(evt.target.id)
secondMove.classList.add('open', 'show')
console.log('second card was clicked')
})
答案 0 :(得分:0)
快速解决方案是在evt.currentTarget上设置一个属性,该属性引用处理程序所在的dom节点。
https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
答案 1 :(得分:0)
一种简单的方法是将类设置为单击的li。
function flipFirst(e) {
if (e.target && e.target.nodeName == "LI") {
var firstMove = document.getElementById(e.target.id)
firstMove.classList.add('open', 'show', 'wasClicked') // Add class if clicked
console.log('first card was clicked')
e.currentTarget.removeEventListener('click', flipFirst);
}
}
cd.addEventListener('click', function(evt) {
if (evt.srcElement.classList.contains('wasClicked') == true) { // check if it has the class
//then prevent default
}
var secondMove = document.getElementById(evt.target.id)
secondMove.classList.add('open', 'show')
console.log('second card was clicked')
})
答案 2 :(得分:0)
或者在javascript中设置一个布尔变量
const cd = document.getElementById('listDeck')
cd.addEventListener('click', flipFirst, false)
var isBtnClicked = false; // <-- Here is variable declared.
function flipFirst(e) {
if (e.target && e.target.nodeName == "LI") {
var firstMove = document.getElementById(e.target.id)
firstMove.classList.add('open', 'show')
console.log('first card was clicked')
e.currentTarget.removeEventListener('click', flipFirst);
}
}
cd.addEventListener('click', function(evt) {
if () {
//condition is true
//then prevent default
}
var secondMove = document.getElementById(evt.target.id)
secondMove.classList.add('open', 'show')
console.log('second card was clicked')
isBtnClicked = true; // <--- Here is the variable
})