我有一个嵌套的HTML列表,并且正在尝试获取.last()
<li>
顶级列表<ul>
。
这就是翡翠的样子
#menu
ul: li
a(href='#') Work (Top Level List 1)
ul: li
a(href='#') Project 1
ul: li
a(href='#') Project 1.1
ul: li
a(href='#') Project 1.1.1
ul: li
a(href='#') Project 1.1.1.1
ul
li: a(href='#link') Project 1.1.1.1.1
li: a(href='#link') Project 1.1.1.1.2
li: a(href='#link') Project 1.1.1.1.3
li: a(href='#link') Project 1.1.1.2
li: a(href='#link') Project 1.1.1.3
li: a(href='#link') Project 1.1.2
li: a(href='#link') Project 1.1.3
li: a(href='#link') Project 1.2
li: a(href='#link') Project 1.3 <- (Last li of top level list)
li
a(href='#') Resume (Top Level List 2)
ul
li: a(href='#link') Resume 1
li: a(href='#link') Resume 2
li: a(href='#link') Resume 3 <- (Last li of top level list)
li
a(href='#') Contact (Top Level List 3)
ul
li: a(href='#link') Contact 1
li: a(href='#link') Contact 2
li: a(href='#link') Contact 3 <- (Last li of top level list)
我<li>
用这个jQuery(使用CoffeeScript)得到了想要的。
$li = $this.find('li')
$liLastChild = $li.find(':last-child').children('a')
$scope = $this.find($li).find($ul)
$scopeNot = $scope.find($li).find($ul)
$this.find($scope).not($scopeNot).each ->
$(this).find($liLastChild).last().css('background', 'orange')
但我需要使用类似以下内容的选择器来检查这些选择器:
if $(this).is($orangeListItem)
当我拿出每个喜欢:
$this.find($scope).not($scopeNot)
.find($liLastChild).last().css('background', 'orange')
jQuery在末尾获得了最后一个<li>
,而不是将其范围限定为期望的<ul>
。
有没有更好的方法来做我想做的事情,最好不要做.each()
,所以我可以将其存储到$orangeListItem
?
编辑:我中途解决了我的问题。我仍然愿意改善这一点。我不确定这是一个很好的解决方案。
我将每个循环存储在变量中,然后使用它:last
来获取最后一个列表项。.last()
由于某种原因将无法正常工作?如果:last
在循环中添加,它也将不起作用。
这就是每个循环现在的样子。
$lastLast = $this.find($scope).not($scopeNot).each ->
$(this).find($liLastChild) # Gather items
$lastLast = $lastLast.find(':last') # Get last list item
$lastLast.css('background', 'orange') # Make them orange
如果我理解正确,则可以使用以下方法:
var $targets = $('#menu > ul > li > ul > li:last-child').not(':has(ul)');
这会大量使用直接子选择器,然后使用jQuery的not()过滤器来排除任何顶级li元素(如果它们具有嵌套的ul)(例如,“ Project 1”)
您可以在jsfiddle上看到一个示例。
编辑:
好吧,棘手的部分也正在获得“项目1.3”,或者无论第一个列表中的最后一个列表项目是否在“工作”中。我需要每个顶级列表的绝对最后一个li。
对不起,忽略了那个。我认为单个CSS选择器无法包含该项目。这个怎么样:
// This variable will store all target <li> as we find them
var $targets = $();
// Loop through each top level <li> to grab the last <li> nested within each
$('#menu > ul > li').each(function () {
var $nested_li = $(this).find('li');
// If any nested <li> are found then we want the last <li>
if ($nested_li.length) {
$targets = $targets.add($nested_li.last());
}
});
// The $targets variable should now contain all relevant <li> items
$targets.css('background', 'orange');
我也更新了演示小提琴。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句