javascript - 类型错误 : undefined is not an object only in Safari and iOS
<p><p>我的以下代码在 Chrome 中运行良好,但在 Safari 中出现以下错误。有什么办法可以解决吗?</p>
<pre><code>jQuery('.mk-responsive-nav > li > a').click( function() {
var href = jQuery(this).attr('href').replace('#', '');
jQuery(window).scrollTop( jQuery("section").offset().top );
console.log( jQuery("section").offset().top);
});
</code></pre>
<p>Safari 错误:</p>
<p>TypeError: undefined is not an object (evalating 'jQuery("section").offset().top')</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>很难说,因为我看不到上下文 html。我建议在滚动 <code>window</code> 之前 try catch<code>href</code> 变量并确保它实际上是一个 <code>jQuery 对象</code>。我确实遇到了同样的错误。</p>
<p></p><div class="snippet"data-lang="js"data-hide="false"data-console="true"data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() {
jQuery('.mk-responsive-nav > li > a').click(function() {
var href = jQuery(this).attr('href').replace('#', '');
var target = jQuery("section");
console.log(target.offset().top, 'YOUR EXACT ERROR IN SAFARI WHEN CLICKING FAIL LINK: ', jQuery("section"));
if (target.length) {
console.log('scrolling to: ', target.offset().top);
jQuery(window).scrollTop(target.offset().top);
}
});
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><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></code></pre>
<p style="font-size: 20px;">关于javascript - 类型错误 : undefined is not an object only in Safari and iOS,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/38026407/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/38026407/
</a>
</p>
页:
[1]