简体   繁体   English

Javascript 函数不会产生预期的结果

[英]Javascript function won't yield expected result

So I have a Javascript function that is supposed to yield the item's nth child.所以我有一个 Javascript 函数应该产生项目的第 n 个孩子。 Below is the code for the function.下面是该函数的代码。

 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; } }

From your element, the algorithm you want might look something like this从你的元素来看,你想要的算法可能看起来像这样

  1. Look at the next sibling element, elm看下一个兄弟元素, elm
  2. If elm is undefined or null return null如果elm未定义或为null 则返回null
  3. If elm has class interestingClass , decrease n by 1如果elm有类InterestClass ,则将n1
  4. If n is greater than 0 go back to step 1如果n大于0则返回步骤 1
  5. Return elm回归elm

Vanilla,香草,

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;
}

Usage, eg on this page用法,例如在此页面上

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