原型 - 优雅的代码,以找到下一个兄弟

时间:2009-09-09 12:25:25

标签: javascript prototypejs

有以下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');                    
                    }    
                );    
            }

        }
    );       
} 

如何改进此代码?

3 个答案:

答案 0 :(得分:0)

对我来说似乎没问题,但我不得不说你的问题非常具有争议性。你的问题没有明确的答案。

答案 1 :(得分:0)

我认为你可以做到:

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

此代码将获得el下具有className“open”的第一个P标记,检查是否存在下一个兄弟P标记,如果存在,则将其className设置为“open”并删除来自上一个标签的className。

答案 2 :(得分: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');
}