这个JavaScript函数可以重构吗?

时间:2010-10-02 17:04:59

标签: javascript optimization prototypejs

我需要在项目中使用原型JavaScript库,并希望将标签框添加到HTML。

点击处理程序有一个简单的任务 - 在父<li>元素上选择并显示链接的DIV id元素(<li>上的rel标签具有元素ID名称)

<div class="tabInterface">
  <ul class="tabSelector">
     <li class="selected" rel="searchLast"><a href="#">Popularna iskanja</a></li>
     <li rel="searchMine"><a href="#">Moje zadnje iskanje</a></li>
  </ul>
  <div class="tabContent selected" id="searchMine">
      box 1 content
  </div>
  <div class="tabContent" id="searchLast">
     box 2 content

  </div> 
</div>

辛苦劳动1小时后的最终结果。

initTabInterface = function() {
    //requires prototype
    var tabClick = function(event){
        Event.stop(event);
        var $el = Event.element(event);

        var $menu = $el.up('.tabSelector');
        var liList = $menu.descendants().filter(function(el){return el.match('li')});
        liList.invoke('removeClassName', 'selected');
        $el.up().addClassName('selected');

        var rel = $el.up().readAttribute('rel');
        var $interface = $menu.up('.tabInterface');
        var tabList = $interface.descendants().filter(function(el){return el.match('.tabContent')});
        tabList.invoke('removeClassName', 'selected');
        $interface.down('#'+rel).addClassName('selected');
    };

    $$('.tabInterface .tabSelector li a').each(function(el){
        var $el = $(el);
        Event.observe($el, 'click', tabClick);
    });
};
Event.observe(window,"load", function(){
    initTabInterface();
});

是否有更简单的遍历原型的方法,而不是使用一堆up,down,filter,match,invoke和每个?

2 个答案:

答案 0 :(得分:1)

这几乎是你可以得到的:

initTabInterface = function() {
    //requires prototype
    var tabClick = function(event){
        Event.stop(event);         
        var $el = Event.element(event);
        var rel = $el.up().readAttribute('rel');

        // remove old selected classes
        $el.up('.tabInterface').select('.selected')
                               .invoke('removeClassName', 'selected');

        // add new selected classes
        [ $(rel), $el.up() ].invoke('addClassName', 'selected');
    };

    $$('.tabSelector li a').each(function(el){
        Event.observe($(el), 'click', tabClick);
    });
};
Event.observe(window,"load", function(){
    initTabInterface();
});​

答案 1 :(得分:0)

我不太了解Prototype以便快速重构您的代码,但您可以使用Element.siblings而不是上升然后下降。或者,您可以按类名枚举(如果您有多个制表符控件,则效果不佳)。

$el.siblings().invoke('removeClassName', 'selected');

另外

$interface.down('#'+rel).addClassName('selected');

是不必要的,因为在整个文档中只能有一个带id的元素。可以改为:

$(rel).addClassName('selected');
相关问题