OGeek|极客世界-中国程序员成长平台

标题: javascript - 类型错误 : undefined is not an object only in Safari and iOS [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 16:49
标题: javascript - 类型错误 : 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: undefined is not an object (evalating 'jQuery("section[data-anchor='"+ href + "']").offset().top')



Best Answer-推荐答案


很难说,因为我看不到上下文 html。我建议在滚动 window 之前 try catch href 变量并确保它实际上是一个 jQuery 对象。我确实遇到了同样的错误。

$(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>

关于javascript - 类型错误 : undefined is not an object only in Safari and iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38026407/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (https://ogeek.cn/) Powered by Discuz! X3.4