创建一个系统,在每次提交错误答案时将“错误”计数器的值增加 1。我通过让我的系统监听一个名为“incorrectResponse”的类的创建来做到这一点。但是,它似乎只是在页面加载完成后立即添加到计数器中,之后不再添加任何值。
这是我试过但不起作用的代码。
//*-- Fault counter --*//
if (document.querySelectorAll('incorrectResponse')) {
$('#fault-counter').html(function(i, val) { return val*1+1 });
};
为什么会这样?
最佳答案
假设您正在使用 jQuery(您在评论中提到了它),您可以做的一件事是将事件监听器附加到“错误答案”的容器。
只要收到错误答案/将错误答案附加到页面,就会手动触发自定义事件,事件监听器会对其使用react,重新计算错误答案的数量并更新计数器。
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>
关于javascript - 在类创建/追加时将计数器的值增加 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40682729/