@unsstrennen

Почему не работает js для элементов, вставленных в документ с помощью innerHTML?

На сайте есть степпер типа <input type="number"
У него есть обработчик на js. Если вставить его на сайт просто так, то он работает. Если добавлять его с помощью innerHTML, то js перестает работать. В
$( document ).ready(function() {
});
засунуть пробовал, не помогло.
Степпер брал отседова
Код
<script type="text/javascript">
    function inner_data(data) {
        var names = JSON.parse(data);
        var to_inner = '';
        for (key in names) {
            var id = key;
            var name = names[id];
            var count = cart[key];
            to_inner += '<div class="alert alert-light" role="alert" style="color: black;border-top: ' +
                '1px solid lightgray; border-bottom: 1px solid lightgray;">' +
                '<h4 class="alert-heading">' + name + '</h4><p>Количество: <div class="input-stepper">\n' +
                '    <button class="minus"><i class="fa fa-minus"></i></button>\n' +
                '    <input type="text" value="0" />\n' +
                '    <button class="plus"><i class="fa fa-plus"></i></button>\n' +
                '</div></p></div>';
        }
        return to_inner;
    }


    var cart = JSON.parse(localStorage.getItem('cart'));
    if (cart == null) {
        document.getElementById('empty_cart').style.display = 'table-cell';
    }
    else {
        document.getElementById('not_empty_cart').style.display = 'block';
        var cart = JSON.parse(localStorage.getItem('cart'));
        var ids = Object.keys(cart);
        $.ajax({
            type: "POST",
            url: 'get_goods_data.php',
            data: ids,
            success: function(data){
                document.getElementById('cart_data').innerHTML = inner_data(data);
            }
        });
    }
</script>
<script type="text/javascript">
    var stepper = function () {
        var stepperNumber,
            minusButton;

        return {

            allSteppers: $( '.input-stepper' ),

            // check to see if the input is at '0'...
            checkStepperNumber: function ( thisStepper ) {
                stepperInput = $( thisStepper ).find( 'input' );
                stepperNumber = stepperInput.val();
                decrementButton = $( thisStepper ).find( 'button.minus' );

                if ( stepperNumber === '0' || stepperNumber <= 0 ) {
                    // if so, disable the minus button.
                    decrementButton.prop( 'disabled', true );
                    stepperInput.val( 0 );
                } else {
                    // if number is positive, enable the minus button
                    decrementButton.prop( 'disabled', false );
                }

            },

            init: function () {
                stepper.allSteppers.each( function ( index, element ) {
                    var thisStepperInput = $( element ).find( 'input' );
                    var thisMinusButton = $( element ).find( 'button.minus' );

                    if ( thisStepperInput.val() === '0' || thisStepperInput.val() <= 0 ) {
                        thisMinusButton.prop( 'disabled', true );
                        thisStepperInput.val( 0 );
                    } else {
                        // if number is positive, enable the minus button
                        thisMinusButton.prop( 'disabled', false );
                    }
                });
            }

        }
    }();

    // on button.plus click ...
    $( '.input-stepper button.plus' ).on( 'click', function ( e ) {
        thisStepper = $( e.target ).closest( '.input-stepper' );
        stepperInput = thisStepper.find( 'input' );

        // check the input value
        stepperNumber = stepperInput.val();

        // increment the input value
        stepperNumber++;
        stepperInput.val( stepperNumber );

        // then check the stepper number
        stepper.checkStepperNumber( thisStepper );
    });

    // on button.minus click ...
    $( '.input-stepper button.minus' ).on( 'click', function ( e ) {
        thisStepper = $( e.target ).closest( '.input-stepper' );
        stepperInput = thisStepper.find( 'input' );

        // check the input value
        stepperNumber = stepperInput.val();

        // decrement the input value
        stepperNumber--;
        stepperInput.val( stepperNumber );

        // then check the stepper number
        stepper.checkStepperNumber( thisStepper );
    });

    // on input field blur ...
    $( '.input-stepper input' ).on( 'blur', function ( e ) {
        thisStepper = $( e.target ).closest( '.input-stepper' );
        // check the stepper number
        stepper.checkStepperNumber( thisStepper );
    });

    // check the stepper number on load
    if ( $( '.input-stepper' ).length ) {
        stepper.init();
    }
</script>
  • Вопрос задан
  • 348 просмотров
Решения вопроса 1
@unsstrennen Автор вопроса
В итоге я попробовал применить append, но это также не увенчалось успехом. В итоге я добавил кнопкам атрибут onclick="stepper_pressed(this)", и это помогло. Передавая аргумент this в функцию, я узнавал, на какую кнопку (+ или -) нажал человек, и к какому степперу добавить или отнять значение.
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 3
Robur
@Robur
Знаю больше чем это необходимо
Раньше было live() для этого.
https://api.jquery.com/live/
теперь это устарело но можете почитать в чем принцип и как правильно использовать
https://api.jquery.com/on/
чтобы получить тот же эффект. Event delegation вам в помощь
Ответ написан
Комментировать
Vlad_IT
@Vlad_IT Куратор тега JavaScript
Front-end разработчик
Ну, выполните скрипт этого "степпера" после изменения innerHTML.
Ответ написан
@AlexRas
$(document).on('click', '.input-stepper button.plus', function ( e ) {}
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы