douyan0732 2013-05-18 10:53
浏览 44
已采纳

为什么我的jQuery preventDefault()工作不正常?

I'm developing a Wordpress theme which uses a self-built jQuery accordion for navigation:

// jQuery Footer Navigation Slide
jQuery('#footer-accordion > li > a').on('click', function(e){
    if(jQuery(this).parent().has('ul')) {
        e.preventDefault();
        if(!jQuery(this).hasClass('open')) {
            jQuery('#footer-accordion li ul').slideUp(350);
            jQuery('ul li a').removeClass('open');
            jQuery(this).next('ul').slideDown(350);
            jQuery(this).addClass('open');
        } else if(jQuery(this).hasClass('open')) {
            jQuery(this).removeClass('open');
            jQuery(this).next('ul').slideUp(350);
        }
    }
});

This worked just fine when i built it in bare HTML, I'm now however having trouble integrating it into my Wordpress theme. It seems the e.preventDefault() I've got in there is also preventing the default (follow the link) on menu items (ul li a) that do NOT have a ul inside. I figured my selectors were fine, since it worked in my HTML.

So in short: I expect to be directed to a page if I click a ul li a where the li has no nested ul. However, nothing happens when I do so. The .slideUp() function works just fine, and I can click the links that are in the nested ul. Are my selectors wrong? Am I giving the wp_nav_menu() function the wrong variables?

This is the relevant part from footer.php:

    <?php wp_nav_menu( array(
        'container_class'   => 'footer-navigation clearfix',
        'menu_id'           => 'footer-accordion' 
)); ?>

And this is what Wordpress makes of that: http://jsfiddle.net/vKmfu/

  • 写回答

1条回答 默认 最新

  • douba9776 2013-05-18 11:29
    关注

    The jQuery(this).parent().has('ul') part is the culprit. This invocation always returns a jQuery object, like most of the jQuery functions. When a JavaScript object is used in a booelan context, it is evaluated as true unless it is null. What you need is if(jQuery(this).parent().has('ul').length > 0) { ... }

    By the way, the selector '#footer-accordion > li > a' won't affect the second or more level of links. The > is a children selector. You probably need a descendant selector.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试