如果语句在控制台中有效,而不是在源代码中

If statement works in console, not in source

我在点击函数中有以下 if 语句:

$('#rent-link').on('click', function() {
  $('.house-card:not(.sold)').fadeIn('fast');
  $('.for-sale').fadeOut('fast');
  $('.rental').fadeIn('fast');
  $('.sold').fadeOut('fast');
  $('.comm').fadeOut('fast');
  if ( $('.house-card:visible').length == 0 ) {
    $('#no-results').show();
  }
  return false;
});

所有代码都包含在文档就绪函数中,因此这不是问题所在。我不确定为什么当为此 if 语句设置参数以解析 true 时,它​​总是解析为 false。当我单击 #rent-link 然后 运行 控制台中的 if 语句单独解析为真时。

感谢您的帮助。

编辑:

我用 settimeout 函数更新了我的代码并且它起作用了。你们是对的,谢谢!

这是工作代码:

$('#rent-link').on('click', function() {
            $('.house-card:not(.sold)').fadeIn('fast');
            $('.for-sale').fadeOut('fast');
            $('.rental').fadeIn('fast');
            $('.sold').fadeOut('fast');
            $('.comm').fadeOut('fast');
            setTimeout(function() { 
                if ( $('.house-card:visible').length === 0 ) {
                    $('#no-results').show();
                } 
            }, 500); 
            return false;
        });

if 语句 运行s.

时,可能仍有一些可见的 .house-card 元素

fadeInfadeOut 函数是异步的,在最终将元素设置为 hidden 之前使用一系列间隔淡出不透明度。 if 语句可能在函数完成并实际隐藏元素之前执行。

当您单击按钮然后 运行 控制台中的语句时,您可能花费的时间比实际 运行 执行命令之前淡入淡出功能所花费的半秒更长,因此元素在您 运行 命令之前就已经隐藏了。

要确保 if 语句在动画完成后 运行ning,您可以使用回调函数,如 http://api.jquery.com/fadeout/ 中所述。类似于:

$('.sold').fadeOut('fast', function() {
  if ( $('.house-card:visible').length == 0 ) {
    $('#no-results').show();
  }
});

请注意,这只会确保没有 .house-card.sold:visible 元素。我不确定 .comm.for-sale 是否也在 .house-card 元素上,但如果是的话,可能需要更多时间才能确保 none它们也是可见的。