Кнопка создана с помощью JavaScript, когда кнопка создается снова, событие при нажатии происходит дважды - PullRequest
1 голос
/ 04 августа 2020

У меня есть всплывающее окно (модальное), данные в модальном окне генерируются с помощью JavaScript. Запрос ajax отправляется для получения отображаемых данных

modal with data

when the enable or disable button is clicked, an ajax is sent with this info to to the back-end.

The problem I am having is when the modal closed and then reopened the click action happens twice (if you click on the enable it send the message the amount of times the popup was opened and closed).

This is some of the code that create the modal

$(document).on('click', '.availability', function() {
    $('.availability_modal_table_body').empty();
    var stuff = $(this).data('info').split(',');

    $.ajax({
            type: 'get',
            url: base_url+"catalogs/"+stuff[0]+"/options",
           
            success: function(data) {
                $('.availability_modal_title').text(`Options for ${stuff[1]}`);

                    var string ="";
                for (var i = 0; i < data.avalable.length; i++) {
               string+=` $ {data.avalable [i] .name}  `; if (data.avalable [i] .catalog_id == null) {string + = ` Создать Добавить `; строка + = ` Блок `; } else if (data.avalable [i] .order_id == null) {string + = ` Create Add `; string + = ` Включить `; } else {string + = ` Посмотреть бронирование `; } строка + = ""; } $ ('. availability_modal_table_body'). html (строка); $ ('# модальный_доступность'). модальный ('показать'); }}); 

Это код кнопки блокировки

$(document).on('click', '.ad_disable', function() {
       var stuff = $(this).data('info').split(',');
        $.ajax({
            type: 'get',
            url: base_url+`items/block/${stuff[0]}/${stuff[1]}`,
             headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
            success: function(data) {
                if(data == 1){
                      toastr.success('Item blocked');
                      $(this).hide();
                }else{
                    toastr.warning('Failed - See errors');
                }
            }
        });  
    });

1 Ответ

0 голосов
/ 04 августа 2020

Это происходит потому, что при закрытии модального окна вы не отменяете привязку события щелчка, зарегистрированного для кнопок.

Перед закрытием модального окна вы должны сначала отвязать события щелчка. jQuery ≥ 1,7 , то вы можете отвязать клики, как показано ниже.

$(document).off('click', '.availability')

И для jQuery <1,7 </strong>

 $(document).unbind('click', '.availability')

Для получения дополнительной информации см. Статью: https://api.jquery.com/unbind/

...