为什么方法事件侦听器单击仅在 for 循环中第一次起作用

问题描述 投票:0回答:0

我想在每次点击按钮“slotsAvailables”和“buttonBooking”时运行函数“checkSlotsChoosen”,但它只适用于每个按钮的第一次点击。我添加 console.log 以查看它是如何工作的。 你知道为什么吗?提前谢谢你!


<script>
var buttonBooking = document.querySelector('.pbSubmit');
var slotsAvailables = document.querySelectorAll('.availableslot a');

buttonBooking.classList.add('disable');

function checkSlotsChoosen(){
        var slotsChoosen = document.querySelectorAll('.availableslot.currentSelection');
        var slotsCancel = document.querySelectorAll('.cancel');

        if(slotsChoosen.length === 0){
                buttonBooking.classList.add('disable');
                console.log('disable btn');
        }else{
                buttonBooking.classList.remove('disable');
                console.log('active btn');
        }

        for (let b = 0; b < slotsCancel.length; b++) {
            slotsCancel[b].addEventListener('click', checkSlotsChoosen);
        }
    }



for (let a = 0; a < slotsAvailables.length; a++) {
    slotsAvailables[a].addEventListener('click', checkSlotsChoosen);
}


buttonBooking.addEventListener('click', checkSlotsChoosen);
<script>

javascript for-loop dom addeventlistener onclicklistener
© www.soinside.com 2019 - 2024. All rights reserved.