2016-11-18 21 views
1

創建一個在提交錯誤答案時將「故障」計數器值增加1的系統。我通過讓我的系統傾聽創建一個名爲「incorrectResponse」的類來做到這一點。但是,只要頁面加載完成,它就會立即添加到計數器中,並且在此之後不會再添加任何值。創建課程時將計數器的值增加一個/追加

這是我試過的代碼不工作的代碼。

//*-- Fault counter --*// 
    if (document.querySelectorAll('incorrectResponse')) { 
    $('#fault-counter').html(function(i, val) { return val*1+1 }); 
    }; 

爲什麼會出現這種情況?

+1

_I'm通過讓我聽系統出於對建立一個class_的這樣做呢? –

+0

@Maximus指出,你的事件監聽器在哪裏? –

+1

'incorrectResponse'或'.incorrectResponse' –

回答

1

假設你使用的是jQuery(你在其中一個註釋中提到它),你可以做的一件事是將一個事件監聽器附加到你的「錯誤答案」的容器中。

任何時候收到/附加到頁面上的錯誤答案都會被手動觸發自定義事件,並且事件偵聽器會對它作出反應重新計算錯誤答案的數量並更新計數器。這裏是監聽的代碼 -

function updateNumberOfIncorrectMsgs() { 
 
    $('.counter').text($('.incorrectAnswer').length); 
 
} 
 

 
updateNumberOfIncorrectMsgs(); 
 
var $container = $('.wrongAnswersContainer') 
 
    .on('newWrongAnswerAdded', function() { 
 
    updateNumberOfIncorrectMsgs(); 
 
    }); 
 

 
// The for and setTimeout is only to simulate msgs appended to the page, the important part is the custom event that gets triggered when an element is added. 
 
for (var i = 1; i < 6; i++) { 
 
    setTimeout(function() { 
 
    $container 
 
     .append('<p class="incorrectAnswer">Incorrect answer</p>') 
 
     .trigger('newWrongAnswerAdded'); 
 
    }, 1000 * i); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p>Incorrect answer counter: <span class="counter"></span> 
 
</p> 
 
<div class="wrongAnswersContainer"></div>

+1

這很好,我能夠修改這段代碼來得到我需要的結果。真的很欣賞這一次伴侶的時間! Upvoted! :) –

+0

不客氣,很高興它幫助你:) – acontell