我在我的代码中使用委托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