javascript - 需要时jquery更新功能

标签 javascript jquery

每次单击按钮时都会调用新帖子。 函数通过 AJAX 调用帖子。 每个帖子都有相同的计算器。

发布示例:

<div class="post">
 <div class="a">1</div>
 <div class="b">8</div>
 <div class="sum">x</div>
 <div class="count">Count</div>
<div>

我有一个函数,如果在帖子出现之前调用它,它当然不起作用。换句话说,如果添加了POST,如果在添加帖子后没有调用该函数,则该函数将不起作用。这是因为 javascript 的自然性。 功能示例:

函数加载计数器(){ $(".count").click(function(){ $(this).parent().find(".sum").html(parseInt($(this).parent().find(".a").html())+parseInt($(this).父().find(".b").html()))

})

}

现在,如果每次调用 AJAX 时都会调用该函数 - 浏览器会多次使用它。类似于:

$(".count").click(function(){
 $(this).parent().find(".sum").html(parseInt($(this).parent().find(".a").html())+parseInt($(this).parent().find(".b").html()))
 $(this).parent().find(".sum").html(parseInt($(this).parent().find(".a").html())+parseInt($(this).parent().find(".b").html()))
 $(this).parent().find(".sum").html(parseInt($(this).parent().find(".a").html())+parseInt($(this).parent().find(".b").html()))

})

每个帖子的结果不是 1+8=9,而是 18 或 27 等。

我无法想出解决方案,也许有人可以帮我解决这个问题?

最佳答案

使用事件委托(delegate);将事件附加到动态创建的元素和附加元素或 document 的父元素;将 .siblings() 替换为 $(this).parent().find()

参见

$(document).on("click", ".count", function() {
  $(this).siblings(".sum")
  .html(
    parseInt($(this).siblings(".a").html())
    + parseInt($(this).siblings(".b").html())
  );   
});

或者,如果您需要在每次 $.ajax() 调用之前调用函数,请使用 beforeSend 选项 Getting code to run syncronously that resides inside a function called via an AJAX call

关于javascript - 需要时jquery更新功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41418756/

相关文章:

javascript - 如何从类型化数组中的二进制数据创建 PNG blob?

javascript - 使用类名显示#ID+this.substring(1)(点)

javascript - 使用 <a> 中的 ID 调用函数的解决方法

php - 使光标消失

javascript - 使用 jquery 自动完成时无法触发更改事件

javascript - 如何创建具有淡入淡出效果的随机变化段落?

javascript - 使用 Jquery 禁用 Datepicker 日历图标?

javascript - jQuery - UI Resizable 调整所有子元素及其字体大小

javascript - 更改显示模块模式之外的可配置设置对象

javascript - 在 youtube 中获取视频大小