我正在将 megamenu 从 HTML/CSS/JavaScript 转换为在 WordPress 中工作。我已经创建了一个工作步行器,一切都准备好了。问题是,我无法让 JavaScript 工作。 JavaScript 应该触发顶层 li
单击时打开大型菜单部分,再次单击时将其关闭。
我使用了这个 JavaScript 文件:
var swMegaMenu = (function() {
var $listItems = $( '#sw-hrmenu > ul > li' ),
$menuItems = $listItems.children( 'a' ),
$body = $( 'body' ),
current = -1;
function init() {
$menuItems.on( 'click', open );
$listItems.on( 'click', function( event ) { event.stopPropagation(); } );
}
function open( event ) {
if( current !== -1 ) {
$listItems.eq( current ).removeClass( 'sw-hropen' );
}
var $item = $( event.currentTarget ).parent( 'li' ),
idx = $item.index();
if( current === idx ) {
$item.removeClass( 'sw-hropen' );
current = -1;
}
else {
$item.addClass( 'sw-hropen' );
current = idx;
$body.off( 'click' ).on( 'click', close );
}
return false;
}
function close( event ) {
$listItems.eq( current ).removeClass( 'sw-hropen' );
current = -1;
}
return { init : init };
})();
我已将其插入到 footer.php 中:
<script>
$(function() {
swMegaMenu.init();
});
</script>
问题是我在 footer.php 中收到此错误:
<script>
$(function() { // Uncaught TypeError: Undefined is not a function
swMegaMenu.init();
});
</script>
JavaScript 文件中出现此错误:
var swMegaMenu = (function() {
var $listItems = $( '#sw-hrmenu > ul > li' ), // Uncaught TypeError: Undefined is not a function
$menuItems = $listItems.children( 'a' ),
$body = $( 'body' ),
current = -1;
最佳答案
您正在使用 WordPress 的默认 jQuery 实例,但您没有使用noConflict() wrappers 。
在 noConflict()
模式下,jQuery 的全局 $
快捷方式不可用。这就是您看到未定义
错误的原因。
要解决此问题,您需要将 $
的所有实例替换为 jQuery
,或者使用包装器包装整个函数集。例如:
(function($) {
// Inside of this function, $() will work as an alias for jQuery()
// and other libraries also using $ will not be accessible under this shortcut
})(jQuery);
了解更多 in the Codex .
关于javascript - 如何修复 WordPress 中的 "undefined is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26777737/