[英]How to get empty ol inside li when li is in sub-level of list item in Jquery?
下面的代碼片段,我試圖獲取並突出顯示包含空ol
元素(沒有任何li
元素的ol
)的每個li
,而不li
級別的數量。
$(document).ready(function() { var Text = ''; var emptyLiText = ''; $('ol#myUL > li').each(function() { lenOl = $(this).find('ol').length; if (lenOl > 0) { lenOlLi = $(this).find('ol').children('li').length; if (lenOlLi == 0) { $(this).addClass('error_item'); emptyLiText = $(this).clone() //clone the element .children() //select all the children .remove() //remove all the children .end() //again go back to selected element .text(); emptyLiText = $.trim(emptyLiText); Text += ' ' + emptyLiText; $('.message').html('<div class="alert alert-danger">' + '<button type="button" class="close" data-dismiss="alert">×</button><b>Unable to Save:</b> Menu item <b>' + Text + '</b> is parent item but does not has sub-item inside.</div>'); breakout = true; // return false; } else { ($(this).hasClass('error_item') == true) ? $(this).removeClass('error_item'): ''; } } }) })
.error_item { border: 1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/js/bootstrap.min.js" crossorigin="anonymous"></script> <div class="message"></div> <ol id="myUL"> <li>Sample Item 1 <ol> <li>Sample Item 2 <ol></ol> </li> <li>Account</li> </ol> </li> <li>Sample Item 3 <ol></ol> </li> <li>Sample Item 4</li> <li>Sample Item 5 <ol> <li>Sample Item 6 <ol> <li>Sample Item 7 <ol></ol> </li> </ol> </li> </ol> </li> </ol>
但是,目前我的嘗試只能得到第一級的li
,里面有空的ol
。 當空的ol
在列表的第二級或第三級時,它會被忽略,例如。 樣品2和樣品7。
我的問題是怎樣才能得到空ol
內li
無論有多少子級是嗎? 因為我的項目與此有關。 謝謝。
你正在使用$('ol#myUL > li')
選擇器,其中>
表示直接孩子。
將>
替換為空格以獲取父<ol>
中所有<li>
元素的<ol>
像這樣的東西$('ol#myUL li')
...獲取並突出顯示包含空ol元素的每個li
普通香草JS
const emptyOl = [].prototype.filter.call(document.querySelectorAll('ol'), el => el.childNodes.length < 1)
const liOfEmptyOl = [].prototype.filter.call(emptyOl, el => el.parentNode.tagName == 'LI')
const highLighted = [].prototype.map.call(liOfEmptyOl, el => el.classList.add('highlighted'))
if (liOfEmptyOl.length > 0) console.error('Danger')
CSS
.highlighted {border: 1px solid red}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.