2014-01-10 83 views
1

獲得一個.TOP未定義或爲空的錯誤在IE9以下代碼:.TOP jQuery的問題與空.TOP

jQuery('#menu').menu(); 
jQuery('#menu').find('a').click(function(e){ 
    if(jQuery(window).width() < 767) { 
     jQuery('#menu').toggleClass('show'); 
    } 
    var $go_to = jQuery(this).attr('href'); 
    var param = $go_to.split('#')[1]; 
    var $go_to_url = $go_to.split('#')[0]; 
    var $current_url = window.location.href.split('#')[0];  
    var scroll_distance = jQuery('#'+param).offset().top; 
    function cleanURL(url) { 
      if(url.match(/http:\/\//)) 
      { 
       url = url.substring(7); 
      } 
      if(url.match(/^www\./)) 
      { 
       url = url.substring(4); 
      } 

      return url; 
    } 
    $go_to = cleanURL($go_to_url); 
    $current_url = cleanURL($current_url); 
    if(jQuery(this).closest('#menu').hasClass('render')) { 
     if(param) { 
      e.preventDefault(); 

      if(jQuery('#'+param).length > 0) { 

       if(jQuery(window).width() > 767){ 
        if(jQuery('.header').hasClass('sticky')){ 
         scroll_distance = scroll_distance - jQuery('.header').outerHeight(); 
        } else { 
         scroll_distance = scroll_distance; 
        } 
       } 

       if($go_to == $current_url) { 

        jQuery('html, body, document').stop().animate({scrollTop: scroll_distance }, 1000, 'easeOutQuart', function(){ 
         window.location.hash = param; 
         jQuery('html, body, document').stop().animate({scrollTop: scroll_distance }, 0); 
        }); 
       } 
       else { 
        window.location = $go_to_url+'#'+param; 
       } 
      } else { 
       window.location = $go_to_url+'#'+param; 
      } 
     } else { 
      window.location = $go_to_url; 
     } 
    } 
}); 

請幫幫忙!基本上,菜單應該能夠點擊到「單頁」網站上的適當部分。但是也有單個博客文章的子頁面。在這些單獨的博客帖子頁面上,當點擊菜單項時,會引發錯誤。我的看法是,它與這些子頁面上沒有param(也不是空白參數)有關,而是一個子頁面url。思考?

+1

'的console.log(jQuery的( '#' + PARAM)。長度)' –

+0

中頻由Kevin B發佈的代碼=== 0,那麼'offset()'是未定義的。基本上確保你的參數是有效的。 –

+1

內置了'location.hash'這樣的東西? – adeneo

回答

2

我建議將下面一行:

var scroll_distance = jQuery('#'+param).offset().top;

像這樣的東西:

var scroll_distance = jQuery('#'+param).length ? jQuery('#'+param).offset().top : 0;

如果jQuery('#'+param)沒有返回對象,然後.offset()是不確定的。

這樣,那麼你可以測試是否scroll_distance定義,只有你嘗試其他動作時,它是:

if (scroll_distance) { 
    //your logic goes here 
} 
+0

這工作!謝謝!!! – mrpritchett