2009-09-09 61 views
0

有以下HTML結構原型 - 優雅的代碼找到一個同級

<div> 
    <p class="open">some txt</p> 
    <p>some text 2</p> 
    <p>some text 3</p> 
    <a href="javascript:;" onclick="down(this.parentNode)">Down</a> 
</div> 

,當我按下我想移動類「開」到下一個P標籤, 這裏是做到這一點的代碼,但我並不認爲它是最優雅的解決方案

function down(el){ 
    el.getElementsBySelector("p.open").each(

     function(s){ 

      s.removeClassName('open'); 

      if (s.next('p')){      
       s.next('p').addClassName('open'); 
      } 
      else{ 
       el.getElementsBySelector("p:first").each(
        function(e){ 
         e.addClassName('open');      
        }  
       );  
      } 

     } 
    );  
} 

該代碼如何改進?

回答

0

對我來說似乎沒問題,但我不得不說你的問題很有爭議。你的問題沒有明確的答案。

0

我覺得你可以做:

function down(el) { 
    var currentOpenP = el.down('p.open'); 
    var nextPSibling = currentOpenP.next('p'); 
    if (nextPSibling) { 
    currentOpenP.removeClassName('open'); 
    nextPSibling.addClassName('open'); 
    } 
} 

此代碼將得到第一個p標籤在你的el其中有一個className「打開」,檢查是否有下一個兄弟p標籤存在,如果它,將其className設置爲「打開」並從前一個標記中刪除className。

0

試試這個:

function down(el){ 
    var selected = el.down('p.open'); 
    el.select('p.open').invoke('removeClassName', 'open'); 

    var next = selected.next('p'); // select next p 
    if(!next) next = el.down('p'); // if next doesn't exists, use the first one 

    next.addClassName('open'); 
}