且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

调用Ajax之后,脚本无法在部分视图上运行

更新时间:2022-11-21 10:41:47

问题:您将事件直接绑定到元素,因此,当您删除该元素并将其替换为另一个元素时,事件就是也与该元素一起删除,这就像是强耦合.

Problem: You are binding event to elements directly, So when you remove this element and replace it with a different one the events are also removed along with that element, This is something like strongly coupled.

解决方案::使用 Jquery事件委托 .这样可以确保事件将在当前元素以及将来可能出现的所有元素上触发.

Solution: Use Jquery event delegation. This will make sure the events will be triggered on the current elements and also all the elements that can come in future.

语法如下.

$(document).on("click", ".btn.btn-sm.btn-default",function () {
    var imageId = $(this).attr("data-image-id");
    albumClient.server.like(iamgeId);
});

注意:这从来不是单个问题,而是Jquery问题.

NOTE: This was never a singlaR issue, it was Jquery issue.

有效方式:使用$(document).on("click"...的问题在于,当整个页面上发生点击时,Jquery框架都会将事件从clicked元素(其父元素和除非选择器中指定的元素到达,否则其性能会受到影响,因为如果我们在所需区域之外单击(在此示例中为按钮.btn.btn-sm.btn-default),我们不希望运行此检查. .

Efficient Way: The problem in using $(document).on("click"... is that when ever there is a click happening on the entire page the Jquery framework will bubble the events from the clicked element upwards(its parent, and its parent and so on..) unless the element specified in the selector arrives, So its kind of performance hit as we don't want this check's to run if we are clicking outside the required area ( button .btn.btn-sm.btn-default in this example).

因此,***做法是将此事件委托绑定到可能不会被删除的最接近的父对象,此问题为<div class="row infinite-scroll">.因此,仅当在此元素内发生单击时,事件冒泡才会发生,并且一旦到达父元素,事件冒泡也将停止,它起到了事件冒泡的边界的作用.

So best practice is to bind this event delegation to the closest parent possible which will not be removed, <div class="row infinite-scroll"> in this question. So that only when the click happens within this element the event bubbling will happen and also will be stopped once it reaches the parent element,it acts kind of a boundary for event bubbling.

   $('.row.infinite-scroll').on("click", ".btn.btn-sm.btn-default",function () {
        var imageId = $(this).attr("data-image-id");
        albumClient.server.like(iamgeId);
    });