javascript - jquery 中的子 li 选择未选择 li 父元素

标签 javascript jquery html css

我已经编写代码使 li 在 url 的基础上处于事件状态。它工作正常但它在子 li 上失败。它使子 li 处于事件状态,而我希望 top 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>

最佳答案

代替父级使用 .closest():

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

并将其放入文档中:

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

这里我用 .find() 而不是 .children() 稍微改变了你的选择器,因为 .find() 寻找孙子也是,如果你想遍历到父级,那么使用 .closest() 方法。


我已经编写代码使 li 在 url 的基础上处于事件状态

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

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

这应该有效:

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

jQuery(function () {
    var path = window.location.pathname;
    $('a[href*="'+ path +'"]').parents('li').addClass('active');
    jQuery('.flexy-menu').find('li').click(function(){ 
        jQuery(this).closest('li').addClass('active');
    });
});

关于javascript - jquery 中的子 li 选择未选择 li 父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24096199/

相关文章:

java - 无法访问从 FTL 文件中的 modelmap 发送的对象列表

jquery - 快要疯了。使用 jquery 检查复选框时的简单警报

javascript - 检查窗口是否打开并且只打开一个新窗口一次?

javascript - Javascript 中的一个有趣的错误

javascript - 多次上传 PHP

php - 在 PHP 中,我应该如何缩短标题和段落中的长字符串以使其适合固定边界?

javascript - 将 'this' 绑定(bind)到 NavigationBarRouteMapper 不起作用

javascript - 使用包装标题时在顶部显示标题文本

javascript - 动态加载时获取当前正在执行的js文件的url

jquery - 为每第三个元素添加 CSS 样式