jQuery检查元素是否存在

时间:2014-01-26 16:49:05

标签: jquery

如何修改下面的脚本,以便在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");
});

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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');
       }

}