2015-07-02 2 views
0

Я написал этот код для мобильной навигации. Все работает хорошо, но, открывая UL, я хочу, чтобы другие UL закрылись. Кто-нибудь знает, как написать это?Закрыть все остальные UL по клику

скрипкой код: - http://jsfiddle.net/t7gucozm/4/

$('nav > ul li a').on('click', function (ev) { 
    if ($(this).next('ul').length > 0) { 
     if ($(this).hasClass('opened')) { 

     } else { 
      $(this).addClass('opened'); 
      $(this).next('ul').show(); 
      ev.preventDefault(); 
     } 
    } else { 

    } 
}); 
+0

Каков уровень иерархии родительских дочерних элементов? –

ответ

0

Просто используйте:

$('nav > ul li a').on('click', function (ev) { 
    if ($(this).next('ul').length > 0) { 
     if ($(this).hasClass('opened')) { 
      $(".opened").removeClass('opened'); 
     } else { 
      $(this).addClass('opened'); 
      $(this).next('ul').show(); 
      ev.preventDefault(); 
     } 
    } else { 

    } 
}); 
+0

Это не работает - все родительские ul все еще открыты. – Liam

0
$('nav > ul li a').on('click', function (ev) { 
     ev.preventDefault(); 
    if ($(this).next('ul').length > 0) { 
     if ($(this).hasClass('opened')) { 
      $(".opened").removeClass('opened'); 
      $(this).next('ul').hide() 
     } else { 
      console.log($('li')) 
      $('li a').each(function() { 
       $(this).removeClass('opened') 
       $(this).next('ul').hide() 
      }); 


      $(this).addClass('opened'); 
      $(this).next('ul').show(); 

     } 
    } 
}); 
+0

Это не работает - все родительские ul все еще открыты. – Liam

+0

меня отредактировал код ... проверить сейчас –

0

Я уже обработал подобную ситуацию с только CSS

дайте мне знать, если у хочу строгое решение JQuery.

http://jsfiddle.net/arunzo/t7gucozm/5/

ul li ul { 
    display:none; 
} 

nav>ul>li>a:focus+ul{ 
    display:block; 
} 
0
  $('nav > ul li a').on('click', function (ev) { 
       if (!$(this).hasClass('opened')) 
        $('nav .opened').removeClass('opened').next().hide(); 

       if ($(this).next('ul').length > 0) { 
        if ($(this).hasClass('opened')) { 

        } else { 
         $(this).addClass('opened'); 
         $(this).next('ul').show(); 
         ev.preventDefault(); 
        } 
       } else { 

       } 
      }); 
0

Пожалуйста, проверьте это.

Последнее обновление: fiddle.

Я добавил класс = "литий-Lable" для каждого родительского Ли с

как этот

<li> 
     <a class="li-lable" href="#">child4</a> 
      <ul> 
       <li><a href="#">child41</a> 
       </li> 
       <li><a href="#">child42</a> 
       </li> 
       <li><a href="#">child43</a> 
       </li> 
      </ul> 
</li> 

JS -

$('nav ul li a ').on('click', function (ev) { 
if ($(this).next('ul').length > 0) { 

    $(this).parent().siblings().children().not(".li-lable").fadeOut() 

    $(this).next('ul').find('li ul').hide() 
    $(this).next('ul').fadeIn() 

} else { 
    alert('no submenu, redirect'); 
} 

});

Смежные вопросы