繁体   English   中英

jQuery function 每次点击运行多次

[英]jQuery function running multiple times on each click

作为 JS 的一部分,我具有以下功能。

_RenderVendorView将在点击供应商表的一行时触发,它会显示供应商详细信息页面,并且在供应商详细信息视图页面中有一个带有 class .vendorsListButton的按钮,它将 go 返回到供应商表,意味着将触发_RenderVendorsList

    var _RenderVendorsList = function () {

        $(document).on('click', '.vendorsListButton', function () {     
            jQuery.ajax({
                url: "/purchases/render_vendors_list",
                type: "POST",
                success:function(data){
                    $data = $(data); // the HTML content that controller has produced
                    $('#vendorcontainer').hide().html($data).fadeIn();
                    _TableVendors();
                    _RenderVendorForm();
                }
            });
        });
    };

    var _RenderVendorView = function () {

        $(document).on('click', '#tableVendors tbody td:not(:first-child)', function () { 
            if ($(this).index() == 4 ) { 
                // provide index of column in which we want prevent row click here is column of 4 index
                return;
            }
            else{
                var rowdata = $('#tableVendors').DataTable().row($(this).parents('tr') ).data();
                jQuery.ajax({
                    url: "/purchases/render_vendor_view",
                    type: "POST",
                    data: {vendor:rowdata.vendor_id},
                    success:function(data){
                        $data = $(data); // the HTML content that controller has produced
                        $('#vendorcontainer').hide().html($data).fadeIn();
                        _TableBills(rowdata);
                        _TableExpenses(rowdata);
                        _RenderVendorsList();
                    }
                });
            }
        });
    };

现在,问题是第一次点击行打开供应商页面和第一次点击.vendorsListButton go 返回供应商列表,第二次点击行也打开供应商页面,但是当第二次点击.vendorsListButton将运行_RenderVendorsList两次,每次迭代function运行增加...

不知道为什么它来回运行多次。

这个循环有什么问题?

.off() : .off .off()方法删除与 .on() 附加的事件处理程序

你可以这样:

$(document).off('click', '.vendorsListButton').on('click', '.vendorsListButton', function () { 
    //Your event logic here
    ...
}):  

它将首先分离事件,然后附加一个新的事件,以防止重复。

更好的解决方案:由于您使用的是事件委托,因此您可以只附加一次事件,即使对于新添加的行,它也可以工作,因此无需每次都调用_RenderVendorsList()

所以只需删除行_RenderVendorsList(); 那是在另一个事件中,并在开始时调用它一次。

也许像:

var _RenderVendorView = function () {

    _RenderVendorsList();

    $(document).on('click', '#tableVendors tbody td:not(:first-child)', function () { 
    ...
       

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM