如何在ajax调用后初始化动态加载的元素


How to get dynamically loaded elements to initialize after an ajax call?

我使用numericstep .js为我的输入文本框微调器。它工作时,我有以下代码。

<script src="<?= site_url('assets/js/numericstepper.js') ?>"></script>
<script>
$('.continue-participation-btn').click(function(e) {
  e.preventDefault();
  var $form = $('form[name="apr-grade-participation-form"]').serialize();
  $.ajax({
    url: '/ajax/continue_participation',
    type: 'POST',
    data: $form,
    success: function(res) {
      if (res) {
        $('.continuous-section').html(res);
        $('html, body').animate({
          scrollTop: 0
        }, 900, function() {
          $('.participation').removeClass('visible').addClass('completed-section');
          $('.continuous-section').addClass('visible');
        });
      } else {
        alert('Unable to process request');
      }
    }
  });
});
</script>
<label for="">Number of Students</label>
<span class="numeric-stepper" style="display: block;"> 
    <input size="2" class="number-of-day-input" id="day_<?=$part_count;?>" name="partdetail_pk_5[<?=$part_count;?>][day]" type="text" placeholder="000" pattern="[0-9]*" value="">
    <button type="button" name="ns_button_1" maxValue = 999 value="1" class="plus">+</button>
    <button type="button" name="ns_button_2" value="-1" class="minus">-</button>
 </span>

但是,当我使用Ajax加载带有输入微调器文本框的页面时,它不起作用。有人有解决这个问题的办法吗?由于

您需要通过在ajax调用的成功函数中调用$('.numeric-stepper').stepper();来初始化新的旋转器。

$.ajax({
    // other ajax options ...
    success: function(res) {
        if (res) {
            $('.numeric-stepper').stepper();
        ...