我在我的代碼中使用委託jquery,但當它觸發一些事件它不止一次觸發,我知道這是因爲我已經綁定了事件optionclicked類到框 - 主類,但我處於一種情況下,我必須將這些類彼此綁定,因爲使用選項點擊類的內容是動態生成的。 有AY問題的解決,使火災事件只有一次意味着一次通話功能和顯示彈出運一次和後一次數據等等等等JQUERY事件觸發不止一次,當使用委託jquery
$('.boxes-main').on('click', '.optionclicked', function(){
// do something
var timetoclick = parseFloat($('#time').text());
clearInterval(myCounter);
var optionclicked = $(this).attr('data');
var questionid = $(this).attr('data2');
$.post("quesanscheck.php", {
ans : optionclicked,
id : questionid,
time : timetoclick
}, function(data, status) {
alert(data);
if(data == optionclicked)
{
//alert("dfad");
setTimeout(function(){ rightans(); }, 1000);
}
else
{
// wrong ans red
if(optionclicked == 'A')
{
document.getElementById('op1').style.background = "red";
document.getElementById('op1').style.border = "0px";
}
if(optionclicked == 'B')
{
document.getElementById('op2').style.background = "red";
document.getElementById('op2').style.border = "0px";
}
if(optionclicked == 'C')
{
document.getElementById('op3').style.background = "red";
document.getElementById('op3').style.border = "0px";
}
if(optionclicked == 'D')
{
document.getElementById('op4').style.background = "red";
document.getElementById('op4').style.border = "0px";
}
// right ans green
if(data == 'A')
{
document.getElementById('op1').style.background = "green";
document.getElementById('op1').style.color = "white";
document.getElementById('op1').style.border = "0px";
}
if(data == 'B')
{
document.getElementById('op2').style.background = "green";
document.getElementById('op2').style.color = "white";
document.getElementById('op2').style.border = "0px";
}
if(data == 'C')
{
document.getElementById('op3').style.background = "green";
document.getElementById('op3').style.color = "white";
document.getElementById('op3').style.border = "0px";
}
if(data == 'D')
{
document.getElementById('op4').style.background = "green";
document.getElementById('op4').style.color = "white";
document.getElementById('op4').style.border = "0px";
}
setTimeout(function(){wrongans();}, 1000);
}
});
});
可否請您詳細闡述_but但是當它發射一些事件時,它會多次觸發_? –
請在JSFiddle重現此問題。 –
您的元素是否動態生成?如果不是,那麼你不需要使用事件委託,或者這可能是事件傳播的問題。 – Jai