【问题标题】:Mystery "TypeError: navWrap.offset() is undefined"神秘“TypeError:navWrap.offset() 未定义”
【发布时间】:2017-01-01 17:15:34
【问题描述】:

我完全被这个问题所困扰,有人知道问题可能是什么吗?

我想在我的自定义 js 文件(在 Wordpress 中)中添加的代码是:

var navWrap = jQuery('#sidebarnavWrap'),
    nav = jQuery('#sidebarnav'),
    startPosition = navWrap.offset().top,
    stopPosition = jQuery('#footer-three').offset().top - nav.outerHeight();

jQuery(document).scroll(function () {
//stick nav to top of page
var y = jQuery(this).scrollTop()

  if (y > startPosition) {
      nav.addClass('sticky');
      if (y > stopPosition) {
          nav.css('top', stopPosition - y);
      } else {
          nav.css('top', 0);
      }
  } else {
    nav.removeClass('sticky');
} 
});

此代码在 jsfiddle 中完美运行。然而,当在我的 WordPress 网站上使用时,控制台会提到“TypeError: navWrap.offset(...) is undefined

http://jsfiddle.net/ykto7uu9/42/

你们中的任何人都知道可能导致这种情况的原因吗? 非常感谢。

额外信息:我的自定义 js 文件已经包含一个非常简单的工作 jQuery 代码来显示/隐藏文本(没有冲突),我在 functions.php 中使用:

function my_javascripts() {
wp_enqueue_script( 'js.custom', '/wp-content/themes/mytheme-child/js/js.custom.js', array() );
}
add_action( 'wp_enqueue_scripts', 'my_javascripts', 1000 );

【问题讨论】:

  • 我只能猜测该元素可能还不存在,您可以尝试将所有内容放入 $(function() {});
  • 感谢您的宝贵时间和@carloliwanag 的建议,但这没有用。 (也已经尝试过):) Nathan 的回答在下面修复了它。祝你有美好的一天!

标签: javascript jquery wordpress undefined


【解决方案1】:

您正在页面头部加载您的 JS,并且您没有等待就绪回调。代码触发时没有 sidebarnavWrap 元素。

将整个 JS 代码块包装在:

jQuery(document).ready(function() {

    // CODE HERE

});

我还建议对您的 enqueue 脚本调用进行一些调整。

  1. 您正在使用 jQuery,因此将其定义为依赖项
  2. 将脚本移至页脚

更新版本:

wp_enqueue_script( 'js.custom', '/wp-content/themes/mytheme-child/js/js.custom.js', array( 'jquery' ), false, true );

https://developer.wordpress.org/reference/functions/wp_enqueue_script/

【讨论】:

  • 非常感谢您清晰而精彩的回复@Nathan Dawson!用你的更新 enqueue 脚本调用解决了这个问题。再次感谢您的宝贵时间,祝您有美好的一天。
猜你喜欢
  • 2011-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-29
  • 1970-01-01
  • 1970-01-01
  • 2020-01-23
  • 1970-01-01
相关资源
最近更新 更多