on() 无法识别类

on() doesn't recognize a class

本文关键字:识别 on      更新时间:2023-09-26

我遇到了on()的问题。这是我的代码:

<span class="add" id="id_foo" >add this stuff</span>
$(".add").on('click', function() {
    $.post("/toto.com/add.php", { trainning: this.id }, function() {});
    $(this).html("Remove this stuff");
    $(this).removeClass("add").addClass("remove");
    //alert($(this).attr("class"));-->give the good class
});
$(".remove").on('click', function() {
    //doesn't work
    $.post("/toto.com/remove.php", { trainning: this.id }, function() {});
    $(this).html("add this stuff");
    $(this).removeClass("remove").addClass("add");
});

remove的选择器无法识别它,而当我单击带有add类的按钮时,类正在更改。你知道问题是什么吗?

感谢您的帮助!

在动态更改处理程序附加到的类时,需要使用委托的事件处理程序。试试这个:

$(document).on('click', ".add", function() {
    $.post("/toto.com/add.php", { trainning: this.id });
    $(this).html("Remove this stuff").toggleClass("add remove");    
});
$(document).on('click', ".remove", function() {
    $.post("/toto.com/remove.php", { trainning: this.id });
    $(this).html("add this stuff").toggleClass("remove add");
});

根据此 JS 代码所在的script标记的位置,您可能还需要将代码包装在 document.ready 处理程序中。如果它就在</body>标签之前,它将正常工作,如果它在头部,请将其放在$(function() { /* your code here */ });