javascript - ajaxComplete() 内的 .on() 事件处理程序?

标签 javascript jquery ajax

我有这个:

$('.task').on('click', function()
{
    task_id = $(this).data('id');
    console.log('Task id: ' + task_id);
});

但是当通过 ajax 重新加载内容时,这不起作用。即使在 ajax 重新加载后单击不同的元素,task_id 值也保持不变。显然我必须首先将它绑定(bind)到 body 上。

这就是我现在代码中的情况(它按预期工作):

$(document).ajaxComplete(function(event, xhr, settings) {
    $('.task').on('click', function()
    {
        task_id = $(this).data('id');
        console.log('Task id: ' + task_id);
    });
});

但有人告诉我这会重复/加倍 .on('click') 事件的触发器?这是真的?那么我如何知道何时绑定(bind)到直接选择器或绑定(bind)到 document.body 呢? 哪个会更有效率?绑定(bind)到 body 或将事件委托(delegate)放入 ajaxComplete() 中?

我也有点困惑,因为我在同一个 .js 文件内有其他事件处理程序,但在 ajaxComplete() 之外,即使在ajax 重新加载?

最佳答案

您应该使用.on()方法 Event Delegation动态生成元素(内容通过 $.ajax() 更新)/操作选择器时的方法。那么您不需要在 ajaxComplete()

中附加事件处理程序

一般语法

$(document).on('event','selector',callback_function)

示例

$(document).on('click', '.task', function(){
    //Rest of your code
});

您应该使用最接近的静态容器来代替文档

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

关于javascript - ajaxComplete() 内的 .on() 事件处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42688304/

相关文章:

使用ajax调用PHPExcel下载

javascript - 如何在不提交表单的情况下获取输入框的值并将计算出的值放入其他输入框?

php - 完成后的动态列表 2 输入 html json

javascript - 使用ajax调用从php服务器发送图像

jquery - 将 Json 数据传递到 MVC Razor View

javascript - 在焦点上添加一个属性

javascript - 几秒后隐藏 div

javascript - 当 WinJS listview 数据源没有项目时如何显示消息?

javascript - 使用助手渲染 Ember View

javascript - 如何在另一个函数中使用ajax函数响应