gpt4 book ai didi

javascript - 需要时jquery更新功能

转载 作者:行者123 更新时间:2023-12-03 05:20:12 25 4
gpt4 key购买 nike

每次单击按钮时都会调用新帖子。函数通过 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/

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