菜鸟教程小白 发表于 2022-12-11 16:49:49

javascript - 类型错误 : undefined is not an object only in Safari and iOS


                                            <p><p>我的以下代码在 Chrome 中运行良好,但在 Safari 中出现以下错误。有什么办法可以解决吗?</p>

<pre><code>jQuery(&#39;.mk-responsive-nav &gt; li &gt; a&#39;).click( function() {
   var href = jQuery(this).attr(&#39;href&#39;).replace(&#39;#&#39;, &#39;&#39;);
   jQuery(window).scrollTop( jQuery(&#34;section&#34;).offset().top );
   console.log( jQuery(&#34;section&#34;).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(&#39;.mk-responsive-nav &gt; li &gt; a&#39;).click(function() {


    var href = jQuery(this).attr(&#39;href&#39;).replace(&#39;#&#39;, &#39;&#39;);
    var target = jQuery(&#34;section&#34;);

    console.log(target.offset().top, &#39;YOUR EXACT ERROR IN SAFARI WHEN CLICKING FAIL LINK: &#39;, jQuery(&#34;section&#34;));

    if (target.length) {
      console.log(&#39;scrolling to: &#39;, target.offset().top);
      jQuery(window).scrollTop(target.offset().top);
    }
});
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src=&#34;https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js&#34;&gt;&lt;/script&gt;
&lt;ul class=&#34;mk-responsive-nav&#34;&gt;
&lt;li&gt;&lt;a href=&#34;#section-1&#34;&gt;This will work&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;#section-fail&#34;&gt;This will fail&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;section data-anchor=&#34;section-1&#34;&gt;Section 1.&lt;/section&gt;
&lt;section data-anchor=&#34;section-2&#34;&gt;Section 2.&lt;/section&gt;</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]
查看完整版本: javascript - 类型错误 : undefined is not an object only in Safari and iOS