>

동적으로 추가 된 .add 버튼을 클릭하면 데이터에서 선택하기 위해 ajax를 호출하지만 첫 번째 모듈에서 m을 클릭하고 okey를 클릭하면 다음에 두 번째 모듈로 이동하여 클릭하면 ajax가 중복됩니다. 전화를 걸어 실수 한 위치를 모르는 필터 하나 더 추가했습니다. 문제를 해결하도록 도와주세요

여기 코드 :

하나의 모듈 :

$(document).ready(function () {
            $("select").select2();
            var $toggleColumns = $('.toggleColumns');
            var datatableName = "list";
            var $body = $("body");
            var URL = 'xxx';
            var columns = [
                {'data': 'title', 'class': "datatable-row-title"},
                {'class': '',
                    'orderable': false,
                    "mData": "comment_type_value", "mRender": function (data, type, full) {
                        if (data > 0) {
                            return '<label class="details-control" style="width:100%; height:100%;"> ' + translate('t_expand_comment_type_down') + ' </label>';
                        } else {
                            return "";
                        }

                    },
                },
                {'mData': 'item', "mRender": function (data, type, full) {
                        return data;
                    }},
                {'data': 'seller'},
                {'data': 'buyer'},
                {'data': 'cat'},
                {'data': 'comment_type'},
                {'data': 'startts'},
                {'data': 'endts'},
                {'data': 'ts'},
                {'data': 'price'},
                {'data': 'qty'},
                {'data': 'sales'},
            ];
            var order = [];
    <?php if (isset($_GET["filters"])): ?>
                URL_TMP = URL;
                URL_TMP += "?insert=false";
                getAjaxDatatable(datatableName, URL_TMP, columns, order, "transaction");
                URL_TMP = "";
    <?php else: ?>
                getButtonsAfterAdded();
                $body.on("click", ".toggleColumnsButton", function (e) {
                    $("#columnsContainer").toggle("slow");
                    return false;
                });
                $body.on("click", ".remove", function (e) {
                    e.preventDefault();
                    $(this).parent().parent().remove();
                    getButtonsAfterRemove();

                    if ($("#list tbody tr").length > 0) {
                        var validate = validateTransaction();
                        if (validate.status == false) {
                            $.gritter.add({
                                title: tranlate("gritter_title_validate"),
                                text: validate.msg,
                                class_name: 'danger',
                                time: '5000'
                            });
                            loader.popup("hide");
                            return false;
                        }
                        getAjaxDatatable(datatableName, URL, columns, order, "transaction");
                    }

                    resetSelect2();
                });
                $body.on("change", ".commentType", function () {
                    if ($("#list tbody tr").length > 0) {
                        getAjaxDatatable(datatableName, URL, columns, order, "transaction");
                    }
                });
                $body.on("change", ".categories", function () {
                    if ($("#list tbody tr").length > 0) {
                        getAjaxDatatable(datatableName, URL, columns, order, "transaction");
                    }
                });
                $body.on('click', ".add", function (e) {
                    e.preventDefault();
                    var filterID = $(this).parent().prev().find("option:selected").attr("data-filteroptionid");
                    $(".filters").append(filtersHTMLTransactionSelect(filterID));
                    var filterId = $(".filter:last-child .chooseFilter option:not(:disabled)").attr("data-filterOptionId");
                    $(".filter").last().prepend("<div class='col-sm-4 form-group sibling'>" + filtersHTMLTransactionValues(filterId) + "</div>");
                    $(".filter").last().append(getCollectionOfButtons());
                    resetSelect2();
                    transactionDatepicker();
                    getButtonsAfterAdded();
                });
                $body.on("keypress", function (e) {
                    if (e.keyCode == 13) {
                        loader.popup("show");
                        var validate = validateTransaction();
                        if (validate.status == false) {
                            $.gritter.add({
                                title: tranlate("gritter_title_validate"),
                                text: validate.msg,
                                class_name: 'danger',
                                time: '5000'
                            });
                            loader.popup("hide");
                            return false;
                        }
                        getAjaxDatatable(datatableName, URL, columns, order, "transaction");
                    }
                });
                $body.on('click', ".search", function (e) {
                    e.preventDefault();
                    var validate = validateTransaction();
                    if (validate.status == false) {
                        $.gritter.add({
                            title: tranlate("gritter_title_validate"),
                            text: validate.msg,
                            class_name: 'danger',
                            time: '5000'
                        });
                        return false;
                    }
                    getAjaxDatatable(datatableName, URL, columns, order, "transaction");
                });
                $toggleColumns.on('click', function (e) {
                    var column = $('#' + datatableName).DataTable().column($(this).attr('data-column'));
                    column.visible(!column.visible());
                });

                $(".csv").on("click", function (e) {
                    e.preventDefault();
                    var validate = validateTransaction();
                    if (validate.status == false) {
                        $.gritter.add({
                            title: tranlate("gritter_title_validate"),
                            text: validate.msg,
                            class_name: 'danger',
                            time: '5000'
                        });
                        return false;
                    }
                    $.ajax({
                        method: "POST",
                        url: "xxxx",
                        dataType: "JSON",
                        data: {
                            filters: getActiveFiltersTransaction(),
                            format: 1,
                            module_id: <?php echo \kontrola\TransactionActions::$MODULE_ID; ?>
                        },
                        success: function (response) {
                            getAccessMessageWithStatusDataTable(response);
                            getUses();
                            $.gritter.add({
                                title: translate('gritter_title_raports'),
                                text: $("#waitingTimeForFile").html(),
                                class_name: 'success'
                            });
                            $("[data-controller-name=raportsDownloaded]").css({
                                "color": "red"
                            });
                            setTimeout(function () {
                                $(".nav.nav-pills.nav-stacked.nav-quirk").find("[data-controller-name=raportsDownloaded]").css({
                                    color: "#505b72"
                                });
                                $.gritter.removeAll();
                            }, 15000);
                        }
                    });
                });
                $(".xls").on("click", function (e) {
                    e.preventDefault();
                    var validate = validateTransaction();
                    if (validate.status == false) {
                        $.gritter.add({
                            title: tranlate("gritter_title_validate"),
                            text: validate.msg,
                            class_name: 'danger',
                            time: '5000'
                        });
                        return false;
                    }
                    $.ajax({
                        method: "POST",
                        url: "xxx",
                        dataType: "JSON",
                        data: {
                            filters: getActiveFiltersTransaction(),
                            format: 0,
                            module_id: <?php echo \kontrola\TransactionActions::$MODULE_ID; ?>
                        },
                        success: function (response) {
                            getAccessMessageWithStatusDataTable(response);
                            getUses();
                            $.gritter.add({
                                title: translate('gritter_title_raports'),
                                text: $("#waitingTimeForFile").html(),
                                class_name: 'success'
                            });
                            $("[data-controller-name=raportsDownloaded]").css({
                                "color": "red"
                            });
                            setTimeout(function () {
                                $(".nav.nav-pills.nav-stacked.nav-quirk").find("[data-controller-name=raportsDownloaded]").css({
                                    color: "#505b72"
                                });
                                $.gritter.removeAll();
                            }, 15000);
                        }
                    });
                });
                $body.on("click", "#raportsScroll", function (e) {
                    e.preventDefault();
                    var top = $("[data-controller-name=raportsDownloaded]").offset().top;
                    top = 241 - 65;
                    $('html, body').animate({
                        scrollTop: top
                    }, 1000);
                });
                $body.on("change", ".chooseFilter", function () {
                    var filterId = $(this).find(":selected").attr("data-filterOptionId");
                    $(this).parent().prev().html(filtersHTMLTransactionValues(filterId));
                    //                transactionDefaultStateOptions();
                    transactionDatepicker();
                    resetSelect2();
                });
    <?php endif; ?>
        });

다른 모듈 :

       $(document).ready(function () {
            $("select").select2();
            var $toggleColumns = $('.toggleColumns');
            var datatableName = "list";
            var $body = $("body");
            var URL = 'xxx';
            var columns = [
                {'data': 'title', 'class': "datatable-row-title"},
                {'mData': 'item', "mRender": function (data, type, full) {
                        return data;
                    }},
                {'data': 'price'},
                {'data': 'qty'},
                {'data': 'user'},
                {'data': 'cat'},
                {'data': 'startts'},
                {'data': 'endts'}
            ];
            var order = [];
            getButtonsAfterAdded();
    <?php if (isset($_GET["filters"])): ?>
                URL_TMP = URL;
                URL_TMP += "?insert=false";
                getAjaxDatatable(datatableName, URL_TMP, columns, order, "auction");
                URL_TMP = "";
    <?php else: ?>
                $body.on("click", ".toggleColumnsButton", function (e) {
                    $("#columnsContainer").toggle("slow");
                    return false;
                });
                $body.on("click", ".remove", function (e) {
                    e.preventDefault();
                    $(this).parent().parent().remove();
                    getButtonsAfterRemove();

                    if ($("#list tbody tr").length > 0) {
                        var validate = validateAuction();
                        if (validate.status == false) {
                            $.gritter.add({
                                title: tranlate("gritter_title_validate"),
                                text: validate.msg,
                                class_name: 'danger',
                                time: '5000'
                            });
                            loader.popup("hide");
                            return false;
                        }
                        getAjaxDatatable(datatableName, URL, columns, order, "auction");
                    }

                    $("select").select2("destroy");
                    $("select").select2();
                });
                $body.on("change", ".commentType", function () {
                    if ($("#list tbody tr").length > 0) {
                        getAjaxDatatable(datatableName, URL, columns, order, "auction");
                    }
                });
                $body.on("change", ".categories", function () {
                    if ($("#list tbody tr").length > 0) {
                        getAjaxDatatable(datatableName, URL, columns, order, "auction");
                    }
                });
                $body.on('click', ".add", function (e) {
                    e.preventDefault();
                    var filterID = $(this).parent().prev().find("option:selected").attr("data-filteroptionid");
                    $(".filters").append(filtersHTMLAuctionSelect(filterID));
                    var filterId = $(".filter:last-child .chooseFilter option:not(:disabled)").attr("data-filterOptionId");
                    $(".filter").last().prepend("<div class='col-sm-4 form-group sibling'>" + filtersHTMLAuctionValues(filterId) + "</div>");
                    $(".filter").last().append(getCollectionOfButtons());
                    $("select").select2("destroy");
                    $("select").select2();
                    auctionDatepicker();
                    getButtonsAfterAdded();
                });
                $body.on("keypress", function (e) {
                    if (e.keyCode == 13) {
                        loader.popup("show");
                        var validate = validateAuction();
                        if (validate.status == false) {
                            $.gritter.add({
                                title: tranlate("gritter_title_validate"),
                                text: validate.msg,
                                class_name: 'danger',
                                time: '5000'
                            });
                            loader.popup("hide");
                            return false;
                        }
                        getAjaxDatatable(datatableName, URL, columns, order, "auction");
                    }
                });
                $body.on('click', ".search", function (e) {
                    e.preventDefault();
                    var validate = validateAuction();
                    if (validate.status == false) {
                        $.gritter.add({
                            title: tranlate("gritter_title_validate"),
                            text: validate.msg,
                            class_name: 'danger',
                            time: '5000'
                        });
                        return false;
                    }
                    getAjaxDatatable(datatableName, URL, columns, order, "auction");
                });
                $toggleColumns.on('click', function (e) {
                    var column = $('#' + datatableName).DataTable().column($(this).attr('data-column'));
                    column.visible(!column.visible());
                });

                $(".csv").on("click", function (e) {
                    e.preventDefault();
                    var validate = validateAuction();
                    if (validate.status == false) {
                        $.gritter.add({
                            title: tranlate("gritter_title_validate"),
                            text: validate.msg,
                            class_name: 'danger',
                            time: '5000'
                        });
                        return false;
                    }
                    $.ajax({
                        method: "POST",
                        url: "xxx",
                        dataType: "JSON",
                        data: {
                            filters: getActiveFiltersAuction(),
                            format: 1,
                            module_id: <?php echo \kontrola\AuctionActions::$MODULE_ID; ?>
                        },
                        success: function (response) {
                            getAccessMessageWithStatusDataTable(response);
                            getUses();
                            $.gritter.add({
                                title: translate('gritter_title_raports'),
                                text: $("#waitingTimeForFile").html(),
                                class_name: 'success'
                            });
                            $("[data-controller-name=raportsDownloaded]").css({
                                "color": "red"
                            });
                            setTimeout(function () {
                                $(".nav.nav-pills.nav-stacked.nav-quirk").find("[data-controller-name=raportsDownloaded]").css({
                                    color: "#505b72"
                                });
                                $.gritter.removeAll();
                            }, 15000);
                        }
                    });
                });
                $(".xls").on("click", function (e) {
                    e.preventDefault();
                    var validate = validateAuction();
                    if (validate.status == false) {
                        $.gritter.add({
                            title: tranlate("gritter_title_validate"),
                            text: validate.msg,
                            class_name: 'danger',
                            time: '5000'
                        });
                        return false;
                    }
                    $.ajax({
                        method: "POST",
                        url: "xxxx",
                        dataType: "JSON",
                        data: {
                            filters: getActiveFiltersAuction(),
                            format: 0,
                            module_id: <?php echo \kontrola\AuctionActions::$MODULE_ID; ?>
                        },
                        success: function (response) {
                            getAccessMessageWithStatusDataTable(response);
                            getUses();
                            $.gritter.add({
                                title: translate('gritter_title_raports'),
                                text: $("#waitingTimeForFile").html(),
                                class_name: 'success'
                            });
                            $("[data-controller-name=raportsDownloaded]").css({
                                "color": "red"
                            });
                            setTimeout(function () {
                                $(".nav.nav-pills.nav-stacked.nav-quirk").find("[data-controller-name=raportsDownloaded]").css({
                                    color: "#505b72"
                                });
                                $.gritter.removeAll();
                            }, 15000);
                        }
                    });
                });
                $body.on("click", "#raportsScroll", function (e) {
                    e.preventDefault();
                    var top = $("[data-controller-name=raportsDownloaded]").offset().top;
                    top = 241 - 65;
                    $('html, body').animate({
                        scrollTop: top
                    }, 1000);
                });
                $body.on("change", ".chooseFilter", function () {
                    var filterId = $(this).find(":selected").attr("data-filterOptionId");
                    $(this).parent().prev().html(filtersHTMLAuctionValues(filterId));
                    auctionDefaultStateOptions();
                    auctionDatepicker();
                    $("select").select2("destroy");
                    $("select").select2();
                });
    <?php endif; ?>
        });

<?php endif; ?>

아약스 호출 함수는 다음과 같습니다 :

function filtersHTMLAuctionSelect() {
    var filters = "";
    $.ajax({
        method: "POST",
        url: "xxxxx",
        dataType: "JSON",
        async: false,
        success: function (response) {
            filters += "<div class='filter'><div class='col-sm-4 form-group'>";
            filters += "<select class='form-control chooseFilter' style='width: 100%;'>";
            $.each(response, function (index, value) {
                filters += "<option data-filterOptionId=" + value.id + ">" + translate(value.title) + "</option>";
            });
            filters += "</select>";
        }
    });
    filters += "</div></div>";
    return filters;
}

좋아요. 버튼을 동적으로 추가하면 문제가 해결됩니다.

$body.off('click', '#add').on('click', "#add", function (e) {
$body.off('click', '#search').on('click', "#add", function (e) {

나에게 효과적입니다.

HTML 버튼 그룹 :

<div class="col-sm-4 form-group">
                <div class="col-lg-3"></div>
                <div class="col-lg-1"></div>
                <button class="add btn btn-success btn-quirk col-sm-3" id="add"><i class="glyphicon glyphicon-plus"></i></button>
                <div class="col-lg-1"></div>
                <button class="search btn btn-warning btn-quirk col-sm-3" id="search"><i class="glyphicon glyphicon-search"></i></button>
            </div>


  • 답변 # 1

    전파를 중단해야 할 수도 있습니다. 이것은 버블 링 문제 일 수 있습니다.

    전화 할 때

    e.preventDefault();
    
    

    또한 호출 중지 전파는 코드를 다음과 같이 만듭니다 :

    e.preventDefault();
    e.stopPropagation();
    
    

    자세한 내용은 https://api.jquery.com/event.stoppropagation/

    를 참조하십시오.

    수정 :

    잘못 될 수있는 또 다른 일이 여기 있습니다 :

    $body.on('click', "#add", function (e) {
    
    

    사용해보십시오

    $('#add').on('click', function (e) {
    
    

  • 답변 # 2

    때때로이 문제는 내부에 자식을 포함하는 요소에 대해 ajax 호출을 만들고 자식에 대해서도 반복적으로 호출하는 경우에 나타납니다. 그리고 Thanpa 솔루션을 사용해보십시오- $('#add').on('click', function (e) {

관련 자료

  • 이전 Espresso로 Android 앱에서 UI 테스트를 실행 중인지 감지하는 방법
  • 다음 customsass에서 각도 재질 매트 양식 필드 편집