javascript - $ ('.photos ul li' ).length 在我注入(inject)照片之前输出 0 并在它们出现时输出 5 但当我删除它们时它仍然显示 5

标签 javascript jquery event-handling

当我单击“removePhotos”按钮时,它将输出长度为 li 的照片。最初,当 DOM 加载它们时,它们没有照片,因此它会输出 0,当我单击“显示照片”时,我使用 ajax 来注入(inject)我的照片。在我插入照片并单击“removePhotos”按钮后,它会输出 5,这是我拥有的照片数量,但问题是当我删除照片,然后单击“removePhotos”按钮时,它应该输出 0,但它仍然输出 5。有关的任何建议如何解决这个问题?

我的html

    <div id="paris">
     <h1>CRAPPY CHEESE</h1>
     <button>Get Paris Photos</button>
     <span>Remove Photos</span>
     <ul class="photos">
     </ul>
    </div>

我的 JavaScript

    function Tour(el) {
      var tour = this;
      this.el = el;

     this.hidePhotos = function() {
      alert($('.photos ul li').length);
      $('.photos').fadeOut();
     }

     this.fetchPhotos = function() {
       $.ajax('photos.html', {
          data: {location: $("#tour").data(this.el)},
          success: function(response) {
           this.el.find('.photos').html(response).fadeIn();
          },
          context: tour,
          error: function() {
            this.el.find('.photos').html('<li>There was a problem fetching the latest photos. Please try again.</li>');
          },
          timeout: 3000,
          beforeSend: function() {
            this.el.addClass('is-fetching');
          },
          complete: function() {
            this.el.removeClass('is-fetching');
          }
        });
      };
   var kirt = this.el.on('click.showPhotos', 'button', this.fetchPhotos);
   var pooh = this.el.on('click.removePhotos', 'span', this.hidePhotos);
  }
  $(document).ready(function() { 
     var paris = new Tour($('#paris'));
  });

最佳答案

向 jQuery fadeOut 函数传递一个执行 $(this).remove() 的回调

你的问题是,fadeOut 只是隐藏了你的照片,但它们仍然存在于 DOM 中。

关于javascript - $ ('.photos ul li' ).length 在我注入(inject)照片之前输出 0 并在它们出现时输出 5 但当我删除它们时它仍然显示 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25540942/

相关文章:

javascript - Angular 6 正确初始化自定义输入组件

javascript - React Native - 根据其父答案处理动态表单

javascript - 如何使用 maxlength 在 textarea 中阻止进一步输入

c# - NotifyIcon 是否具有 MouseDown 等效项?

javascript - 是否可以在 Javascript 中动态设置我想绑定(bind)的事件?

javascript - 如何将一个数组创建到另一个数组中?

javascript - 日期和时间范围选择器

jquery - 使整个页面变暗但突出显示某些区域

带有 html 的 javascript 用于粘滞便笺

Javascript 事件监听器问题