【问题标题】:TypeError: undefined is not an object only in Safari and iOSTypeError: undefined is not an object only in Safari 和 iOS
【发布时间】:2016-06-25 08:12:22
【问题描述】:

我的以下代码在 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')

【问题讨论】:

    标签: javascript jquery ios safari scrolltop


    【解决方案1】:

    很难说,因为我看不到上下文 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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-15
      • 2019-03-25
      • 1970-01-01
      相关资源
      最近更新 更多