2016-04-17 10 views
-1

したがって、アイテムのn番目の子を生成するはずのJavascript関数があります。以下はその関数のコードです。Javascript関数は期待した結果を得られません

function findNthChild(element) { 
 
\t nthchild = 1; 
 
\t console.log(element); 
 
\t if (element.prev().hasClass('.point')) { 
 
\t \t while (element.prev().hasClass('.point')) { 
 
\t \t \t nthchild++; 
 
\t \t \t element == element.prev() 
 
\t \t } 
 
\t \t return nthchild; 
 
\t } 
 
\t else { 
 
\t \t console.log('lmao'); 
 
\t \t return 1; 
 
\t } 
 
}

+2

'要素= element.prev();'の代わりに '要素== element.prev();' –

+0

は 'jQueryオブジェクトまたはDOM要素をelement'ていますか? – jfriend00

答えて

0

あなたの要素から、あなたが希望するアルゴリズムは次の兄弟要素で、この

  1. ルックのようなものに見えるかもしれません、elm
  2. elm未定義かである場合null返信null
  3. elmがinterestingClassクラスを持っている場合は、nは1
  4. 戻り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; 
} 

に戻ってください。0よりも大きい場合1

  • nを減らします使用法、例えばこのページの

    var elm = document.querySelector('.kwd'); 
    nthSiblingElementByClass(elm, 5, 'pln'); // <span class=​"pln">​console​</span>​ 
    
  • +0

    これはどのようにn番目の子供ですか?また、あなたはjsfiddleや例のように提供することができますので、私はより良い使い方を理解することができます。 – DarkReaperRising

    関連する問題