在jquery中的子li选择中未选择Li父元素

时间:2014-06-07 10:23:40

标签: javascript jquery html css

我已经编写了代码来使li在url基础上处于活动状态。它工作正常,但它在子li上失败。它让孩子活跃,而我想要顶级li应该是活动而不是child。我的代码如下:

 <script type="text/javascript">
jQuery(function () {
    setNavigation();
});

function setNavigation() {


// this portion code make li active on url basis

    var pathname = window.location.pathname;
    path = pathname.replace(/\/$/, "");
    path = decodeURIComponent(path);

    var value = jQuery(location).attr('href');
//   value  = value.replace('.html', ''); alert(value);
    jQuery(".flexy-menu a").each(function () {
        var href = jQuery(this).attr('href'); 
        if (value === href) { 
            jQuery(this).closest('li').addClass('active');
        }
    });

// this is code for child li but only first code works

    jQuery('.flexy-menu').children('li').click(function(){ 
    jQuery(this).parent('li').addClass('active');
    });

}</script>

我的HTML是这样的:

<ul class="flexy-menu orange">
            <li style=""><a href="http://example.com/">Home</a></li>
            <li style=""><a href="JavaScript:void(0)">Collection</a>
<ul style="">            <li><a href="http://example.com/my-secret-garden.html">My Secret Garden </a></li>
     <li><a href="http://example.com/legend.html">Legend</a></li></ul>
</li>

            <li class="active" style=""><a href="http://example.com/artisans">Artisans</a></li>
            <li style=""><a href="http://example.com/contacts">Contact </a></li>
          </ul>

2 个答案:

答案 0 :(得分:1)

而不是父母使用.closest()

jQuery(this).closest('li').addClass('active');

并将其放入doc准备中:

jQuery(function () {
    setNavigation();
    jQuery('.flexy-menu').find('li').click(function(){ 
        jQuery(this).closest('li').addClass('active');
    });
});

在这里,我使用.find()而不是.children()稍微更改了您的选择器,因为.find()也会查找大孩子,如果您想要遍历父母,那么请使用{{1方法。


我已经编写了代码,以便在网址上激活li

好!然后你可以选择这样做:

.closest()

这应该有效:

总而言之,您只需要这样做,不需要额外的功能:

$('a[href*="'+ path +'"]').parents('li').addClass('active');

答案 1 :(得分:0)

jQuery('.flexy-menu > li').click(function(e){    
jQuery(this).closest('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});

演示:

http://jsfiddle.net/hqPQu/

相关问题