【问题标题】:jQuery check if element exists [duplicate]jQuery检查元素是否存在[重复]
【发布时间】:2014-02-17 10:22:59
【问题描述】:

如何修改下面的脚本,以便在 DOM 中不存在“.fixit”元素时不会引发错误?

function fixedHeaders() {
       var el = jQuery('.fixit'),
           offset = el.offset(),
           elHeight = el.height(),
           scrollTop = jQuery(window).scrollTop()
           if (((offset.top + 400) < scrollTop - el.height())) {
               el.addClass('fixedElement');
           }

       if (scrollTop === 0) {
           el.removeClass('fixedElement');
       }
}
jQuery(function() {
   jQuery(window)
       .scroll(fixedHeaders)
       .trigger("scroll");
});

【问题讨论】:

  • 说真的,搜索时很难找到答案吗?

标签: jquery


【解决方案1】:

开始

if (!jQuery('.fixit').length) return;

【讨论】:

    【解决方案2】:
    if ($('.fixit').length) {
    
         var el = jQuery('.fixit'),
               offset = el.offset(),
               elHeight = el.height(),
               scrollTop = jQuery(window).scrollTop()
               if (((offset.top + 400) < scrollTop - el.height())) {
                   el.addClass('fixedElement');
               }
    
           if (scrollTop === 0) {
               el.removeClass('fixedElement');
           }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2011-06-03
      • 2011-06-15
      • 2015-09-13
      • 2011-11-14
      • 2010-12-03
      • 1970-01-01
      • 2011-06-26
      • 2011-07-14
      相关资源
      最近更新 更多