$('#cherub_sub1_plus').one("click",function(event){
event.preventDefault();
$(this).addClass("cross");
$(this).attr("src","new_image.png");
});
$('.cross').on("click",function(){
// nothing will execute here because I've changed the src
});
这很奇怪。每当您更改图像的src时,所有事件处理程序也会被删除。
答案 0 :(得分:2)
这不是因为您更改了源,因为您动态添加了一个类,并且该事件处理程序是在运行时注册的。使用.on()
$(document).on("click", ".cross", function(){
// nothing will execute here because I've changed the src
});
答案 1 :(得分:0)
尝试重构您的代码:
$('#cherub_sub1_plus').on("click",function(e){
var $this = $(this);
e.preventDefault();
if($this.hasClass('cross')){
// do your magic
} else {
$this.addClass('cross').get(0).src = 'new_image.png';
}
});
这样,它将检查类是否存在,如果它存在,则执行一些魔术,否则添加类并更改图像的src。它还将其整合到一个单击处理程序中,该处理程序不需要$(document)
级别的单击事件(从性能角度来看代价很高)。
我还链接了你的src
的赋值,并出于性能原因使用了vanilla JS方法。无法帮助自己。