簡體   English   中英

Javascript 函數不會產生預期的結果

[英]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; } }

從你的元素來看,你想要的算法可能看起來像這樣

  1. 看下一個兄弟元素, elm
  2. 如果elm未定義或為null 則返回null
  3. 如果elm有類InterestClass ,則將n1
  4. 如果n大於0則返回步驟 1
  5. 回歸elm

香草,

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM