繁体   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