如何在不刷新的情况下停止 class 的事件

how to stop the event of the class without refreshing

我已经为整行使用了事件并通过 ajax 在页面 task.php 中执行了一些功能并更改了样式删除了 class 并在不刷新的情况下显示了消息页 。 尽管我已经删除了 class view_task 它仍然可以正常工作并执行如何防止它的功能。 并且还更改了 class 切换 class(jquery 函数

$('#task tbody tr.view_task').dblclick(function(e){
        var task_id = this.id.split('-');
        var id = this.id;

        $.post('task.php',{'task':task_id[1],'action':'update_count','type':task_id[2],'index':task_id[3]},function(data){
            $('#'+id).css('background-color','white');
            $('#'+id).removeClass( "view_task" );
            $("#message2").html('<span id="msg">Task Viewed <a href="#" id="remove"><img src="images/remove.png" /></a></span>');
        });
       e.preventDefault();
    });

试试这个:

$('#task tbody tr.view_task').unbind();

或者如果您只想删除点击事件

$('#task tbody tr.view_task').unbind("click");
$('#task tbody tr.view_task').dblclick(function(e){});

上面的语句找到了绑定事件的元素,如果你删除selector它不会有影响。

您可以使用 .off() 来删除事件处理程序。

$('#task tbody tr.view_task').dblclick(function(e){
    var self = this;

    $.post('task.php',{'task':task_id[1],'action':'update_count','type':task_id[2],'index':task_id[3]},function(data){
        $(self).off('dblclick')
    });    
});    

,您可以使用Event Delegation using .on()委托事件方法。

$('#task tbody').on('dblclick', 'tr.view_task', function(e){
    //Your code
})

当您安装这样的事件处理程序时:

$('#task tbody tr.view_task').dblclick(function(e){

它最初安装并且将保留在对象上,无论您对对象进行什么 class 更改。

如果您希望事件处理程序是动态的并随着 class 的变化而变化,那么您需要像这样使用 .on() 的委托形式:

$('#task tbody').on("dblclick", "tr.view_task", function(e){...});

这实际上会将事件处理程序附加到 #task tbody,然后每次 dblclick 事件冒泡到该元素时,它都会检查它是否起源于具有 "tr.view_task" 的元素。这将允许它仅在适当的 class 仍在单击的对象上时才响应。

有关委托事件处理的其他信息,请参阅这些参考资料:

JQuery Event Handlers - What's the "Best" method

jQuery .live() vs .on() method for adding a click event after loading dynamic html

Does jQuery.on() work for elements that are added after the event handler is created?

jQuery selector doesn't update after dynamically adding new elements

Should all jquery events be bound to $(document)?

您需要解绑或关闭.view_task的活动class

示例:

$('#task tbody tr.view_task').off('dblclick');

$('#task tbody tr.view_task').unbind('dblclick');

尝试

$("#task tbody tr.view_task").dblclick(function(e) {
    if ($(this).hasClass("view_task")) {
        // do stuff
        $(this).removeClass("view_task")
    };       
    e.preventDefault();
});

$("body").addClass("view_task")
.on("dblclick", function(e) {
    if ($(this).hasClass("view_task")) {
        // do stuff
        console.log(this.className);
        $(this).removeClass("view_task");
    };       
    e.preventDefault();
});
body {
  width:400px;
  height:400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
dblclick