[英]Javascript function won't yield expected result
所以我有一個 Javascript 函數應該產生項目的第 n 個孩子。 下面是該函數的代碼。
function findNthChild(element) { nthchild = 1; console.log(element); if (element.prev().hasClass('.point')) { while (element.prev().hasClass('.point')) { nthchild++; element == element.prev() } return nthchild; } else { console.log('lmao'); return 1; } }
從你的元素來看,你想要的算法可能看起來像這樣
elm
elm
未定義或為null 則返回null
elm
有類InterestClass ,則將n
減1
n
大於0
則返回步驟 1elm
香草,
function nthSiblingElementByClass(sibling, n, cls) {
if (sibling) do {
if (sibling.classList.contains(cls))
if (--n < 0) return sibling;
} while (sibling && (sibling = sibling.nextElementSibling));
return null;
}
用法,例如在此頁面上
var elm = document.querySelector('.kwd');
nthSiblingElementByClass(elm, 5, 'pln'); // <span class="pln">console</span>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.