check if <ul> <li> has an active link?

。_饼干妹妹 提交于 2019-12-25 01:46:23

问题


i have

<ul>
<li class="section-title">HEADER which triggers dropdown</li>
   <li><a href="element_one">element one</a></li>
   <li><a href="element_one">element one</a></li>
   <li><a href="element_one">element one</a></li>
</ul>

i'm hiding all li-elements (except the first one) with this line:

$('#menu ul li.section-title:first-child').parent().children('li').hide();

i wonder if it's possible to query if one of those three links is active and if so nothing should hide!

is that even possible? thank you for your help!


回答1:


  1. Your code will actually hide all li elements (including the first one).
    Use $('#menu ul li:not(:first-child)').hide(); to hide all but the first one..
  2. For the next part (to only hide them if none is the current one) use

    var loc = window.location.href;
    var anyActive = false;
    $('#menu li a').each(function(){
        anyActive = anyActive || (this.href == loc);
    });
    
    if (!anyActive)
        $('#menu ul li:not(:first-child)').hide();
    

Update with working code, after comment

var loc = window.location.href;

$('#menu li a').each(function(){
    if (this.href == loc)
        $(this).addClass('activelink');
});

$('#menu ul:not(:has(.activelink)) li:not(:first-child)').hide();

live example: http://jsfiddle.net/gaby/SMmtS/21/




回答2:


Why not attach a class to the active link, then you could do something like:

$(document).ready(function() { $(".myClass").doSomething();});


来源:https://stackoverflow.com/questions/3153229/check-if-ul-li-has-an-active-link

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!