TypeError:undefined不仅是Safari和iOS中的对象

时间:2016-06-25 08:12:22

标签: javascript jquery ios safari scrolltop

我的以下代码在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不是一个对象(评估' jQuery("部分[data-anchor ='" + href +"']&# 34;)偏移()顶部&#39)

1 个答案:

答案 0 :(得分:0)

很难说,因为我无法看到上下文html。我建议您在滚动href之前尝试捕获jQuery Object变量并确保它实际上是window。我确实设法得到了同样的错误。

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