gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 14:56:18 25 4
gpt4 key购买 nike

我有这个:

$('.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com