2014-05-09 42 views
1

我想为每个页面都有一个脚本文件,其中包含可能或可能不需要特定页面的脚本。在我的主页我有这样的脚本:如果元素不在页面上,则会出现Javascript错误

$(function() { 

var $select = $('#select'); 
var $window = $(window); 
var isFixed = false; 
var init = $('#select').offset().top; 

$window.scroll(function() { 
    var currentScrollTop = $window.scrollTop(); 
    if (currentScrollTop > init && isFixed === false) { 
     isFixed = true; 
     $select.css({ 
      top: 0, 
      position: 'fixed' 
     }); 
     console.log("fixed"); 
    } else if(currentScrollTop <= init && isFixed === true) { 
     isFixed = false; 
     $select.css('position', 'relative'); 
     console.log("unfixed"); 
    } 
}); 

$("#scroll").click(function() { 
    $('html, body').animate({ 
     scrollTop: $(".jumbo").offset().top + $(".jumbo").height() 
    }, 300); 
}); 

}); 

然而,当这个运行在首页(不必须的元素#选择),我得到这个错误,打破我的脚本:

Uncaught TypeError: Cannot read property 'top' of undefined

我怎样才能让它不会导致错误,如果该脚本不需要在该特定页面上,而不必将其加载到它自己的文件中?

我应该在页面加载时调用函数吗?

回答

1

可以使用length属性来检查元素是否存在:

var init = $select.length ? $select.offset().top : 0; 

这将返回0如果元素不存在,否则其顶偏出。

+0

'.length'是要走的路! :) –

相关问题