簡體   English   中英

TypeError:僅在Safari和iOS中undefined不是對象

[英]TypeError: undefined is not an object only in Safari and iOS

我的以下代碼在Chrome中運行正常,但在Safari中出現以下錯誤。 有什么解決方案可以解決。

jQuery('.mk-responsive-nav > li > a').click( function() {
   var href = jQuery(this).attr('href').replace('#', '');
   jQuery(window).scrollTop( jQuery("section[data-anchor='" + href + "']").offset().top );
   console.log( jQuery("section[data-anchor='" + href + "']").offset().top  );
});

Safari錯誤:

TypeError:未定義不是對象(評估'jQuery(“ section [data-anchor ='” + href +“']”)。offset()。top')

很難說,因為我看不到html上下文。 我建議嘗試在滾動window之前捕獲href變量,並確保它實際上是一個jQuery Object 我確實設法得到了同樣的錯誤。

 $(function() { jQuery('.mk-responsive-nav > li > a').click(function() { var href = jQuery(this).attr('href').replace('#', ''); var target = jQuery("section[data-anchor='" + href + "']"); console.log(target.offset().top, 'YOUR EXACT ERROR IN SAFARI WHEN CLICKING FAIL LINK: ', jQuery("section[data-anchor='" + href + "']")); if (target.length) { console.log('scrolling to: ', target.offset().top); jQuery(window).scrollTop(target.offset().top); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="mk-responsive-nav"> <li><a href="#section-1">This will work</a> </li> <li><a href="#section-fail">This will fail</a> </li> </ul> <section data-anchor="section-1">Section 1.</section> <section data-anchor="section-2">Section 2.</section> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM