简体   繁体   English

Javascript如果其他问题移动Jquery切换菜单

[英]Javascript if else problems mobile Jquery toggle menu

I'm trying to make a jquery toggle menu for a mobile website. 我正在尝试为移动网站制作一个jquery切换菜单。

I've managed to create a toggle menu with + and - when toggled and when not 我设法用+和-创建切换菜单

Current version : http://jsfiddle.net/9Dvrr/7/ 当前版本http//jsfiddle.net/9Dvrr/7/

Now i'm trying to create a if else statement fot displaying a ">" when there are no children. 现在,我试图创建一个if else语句,以便在没有子级时显示一个“>”。

Experiment : http://jsfiddle.net/9Dvrr/6/ 实验http//jsfiddle.net/9Dvrr/6/

Problem is that i just can seem to figure it out.. 问题是我似乎可以弄清楚..

Thanks in advance, 提前致谢,

Rick 里克

You need to check the length property when checking if it has children. 检查它是否有子级时,需要检查length属性。 Otherwise, all you're checking is if the result is non-null or not...and it will always be non-null even if the selector doesn't match because it will return jQuery. 否则,您要检查的是结果是否为非null ...并且即使选择器不匹配,结果也始终为非null,因为它将返回jQuery。 It will be empty of any elements, but an object nonetheless and thus non-null. 它将没有任何元素,但是将是一个对象,因此为非null。

if (element.has('ul').children('a').length > 0) {
    element.prepend("<span>+ </span>");

This code below will do what you want, but it could definitely use a little refactor. 下面的代码将执行您想要的操作,但是肯定可以使用一些重构。 It's mostly to show you how you can achieve it simply : 主要是为了向您展示如何轻松实现它:

$('#menu-mobiel ul').hide();

$.each($('#menu-mobiel li'), function(i, value) {
    var $this = $(this);

    if($this.find('ul a').length > 0) {
        $this.find('a').append("<span>+ </span>")
        .addClass('plus')
        .click(function() {
            togglePlus($(this));
            $(this).next('.sub-menu').slideToggle('normal');
        });
    }
    else
    {
        $this.find('a').append("<span>> </span>");
    }
})

function togglePlus(element) {
    element = $(element);
    if (element.hasClass('plus')) {
        element.removeClass('plus').addClass('minus');
        element.children('span').text('- ');
    } else {
        element.removeClass('minus').addClass('plus');
        element.children('span').text('+ ');
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM