我在我的代码中使用委托 jquery,但是当它触发某些事件时,它会触发不止一次,我知道这是因为我已将optionclicked类的事件绑定到box-main类,但我处于我必须的情况将这些类相互绑定,因为使用optionclicked类的内容是动态生成的。是否有解决该问题的方法,以便事件仅触发一次意味着它调用一次函数并显示一次弹出操作并发布一次数据等。
$('.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);
}
});
});