중첩 된 HTML 목록 .last()
<li>
이 있고 최상위 수준 을 가져 <ul>
오려고합니다.
Jade의 모습은 다음과 같습니다.
#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 () 필터를 많이 사용하여 중첩 된 ul (예 : "프로젝트 1")이있는 경우 최상위 li 요소를 제외합니다.
여기 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] 삭제
몇 마디 만하겠습니다