使用jQuery在ul li列表中的所有li块中找到最深和最后一个li? [英] Find the deepest and the last li in any li blocks in a ul li list using jquery?

查看:314
本文介绍了使用jQuery在ul li列表中的所有li块中找到最深和最后一个li?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML列表.有多个嵌套的ul和li.单击li时,我想在li标签中找到最深的项目,里面没有ul标签,并且li是该组中的最后一个项目. 示例以该链接为例

I have a list in HTML. There are several nested ul and li.When I click on a li, I want to find a deepest item in that li tag that has no ul tag inside and the li is the last item of that groups. example follow this link for example

这是我的 HTML 代码.

这是我的方法.

$('.liclk').click(function(){
    $(this).find("li").last().css( "background-color", "red" );
});

我的解决方案是选择最后一个li,而不是最深.

My solution is selecting last li but not the deepest.

我是jquery的初学者.

I am beginner in jquery.

推荐答案

使用while继续查找降序的ul,如果找不到它,请选择其中的最后一个列表项并应用CSS:

Use while to keep looking for a descending ul and when it can find no more, select the last list item within and apply CSS:

$('.liclk').click(function(){
    var $current = $(this).find('ul'),
        $desc = $current;
    while($desc.length){
        $current = $desc;
        $desc = $current.find('ul');
    }
    $current.find('li').last().css('background-color' ,'red')
});

JSFiddle

这篇关于使用jQuery在ul li列表中的所有li块中找到最深和最后一个li?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆