Javascript 事件侦听器在单击箭头后消失
我正在操作一个wordpress插件(蜘蛛日历),以便在单击时更改一些颜色。首次加载页面时,事件侦听器将列在检查器中。单击“2016”、“2018”、左箭头或右箭头时,事件侦听器将从检查器的“事件侦听器”选项卡中消失,尽管它仍显示在源代码中 根据一些研究,我认为这可能是因为元素被破坏了?我该怎么做才能让事件侦听器在每次日历重新加载时都重新加载?还是问题的另一个根源 我的事件侦听器:Javascript 事件侦听器在单击箭头后消失,javascript,jquery,html,css,wordpress,Javascript,Jquery,Html,Css,Wordpress,我正在操作一个wordpress插件(蜘蛛日历),以便在单击时更改一些颜色。首次加载页面时,事件侦听器将列在检查器中。单击“2016”、“2018”、左箭头或右箭头时,事件侦听器将从检查器的“事件侦听器”选项卡中消失,尽管它仍显示在源代码中 根据一些研究,我认为这可能是因为元素被破坏了?我该怎么做才能让事件侦听器在每次日历重新加载时都重新加载?还是问题的另一个根源 我的事件侦听器: if (window.location.href.indexOf("bounce-houses/") > -
if (window.location.href.indexOf("bounce-houses/") > -1) {
var element = $('#afterbig1 table table table tr:nth-child(n+2) td');
element.click(function() {
if ($(this).is(":nth-last-child(2)") || $(this).is(":last-child") || $(this).is(":first-child")) {
$(this).toggleClass("selectedWeekend");
if ($(this).hasClass("calsun_days")) {
$(this).toggleClass("sundays");
$(this).toggleClass("calsun_days");
} else if ($(this).hasClass("sundays")) {
$(this).toggleClass("sundays");
$(this).toggleClass("calsun_days");
}
} else if ($(this).is('td:nth-child(n+2):nth-child(-n+5)')) {
$(this).toggleClass("selectedDays");
}
});
}
});
问题页面:(日历代码太多,无法在此添加)
如果您的元素被销毁,则在重新创建后,没有侦听器会重新连接到它 快速解决方案是将单击事件绑定到始终存在的某个元素,例如
body
请尝试以下操作:
if(window.location.href.indexOf("bounce-houses/") > -1){
$('body').on('click', '#afterbig1 table table table tr:nth-child(n+2) td', function() {
if($(this).is(":nth-last-child(2)") || $(this).is(":last-child") || $(this).is(":first-child")){
$(this).toggleClass("selectedWeekend");
if($(this).hasClass("calsun_days")){
$(this).toggleClass("sundays");
$(this).toggleClass("calsun_days");
}
else if ($(this).hasClass("sundays")){
$(this).toggleClass("sundays");
$(this).toggleClass("calsun_days");
}
}
else if($(this).is('td:nth-child(n+2):nth-child(-n+5)')){
$(this).toggleClass("selectedDays");
}
})
}
});