2012-12-21 150 views
-1

我试图在javascript中简化(或改进)我的代码。简化javascript函数代码

task.prototype.init = function(){ 

     //for loop and create bunch of links 
      var size=document.createElement('a'); 
       size.innerHTML='test' 
       size.id=value; 
       size.onclick=this.changeSize.bind(this); 

       body.appendChild(size); 
} 


task.prototype.changeSize = function(e){ 
    for(var i=0; i<e.target.parentNode.childNodes.length; i++){ 
    e.target.parentNode.childNodes[i].style.backgroundColor='white'; 
    } 
e.target.style.backgroundColor='red'; 
return false; 
} 

我的HTML就像

<div> 
    <a href='#' id='1'>test</a> 
    <a href='#' id='2'>test</a> 
    <a href='#' id='3'>test</a> 
<div> 

我的代码将改变所有的<a>链接,白色的背景色,给选择<a>标签的红色背景。 它适合我需要的,但我有一种感觉,它可以在我的changeSize函数中更漂亮。

有没有更好的方法来写它?非常感谢!

+0

你有没有考虑使用jQuery最大的可爱? – 0x499602D2

+4

尝试在[codereview.se] –

+1

处询问,“Function#bind”在IE <9中不起作用 –

回答

1

使用变量来避免意大利面代码。

task.prototype.changeSize = function(e) { 
    var target = e.target, 
     nodes = e.target.parentNode.childNodes, node; 

    for (var i = nodes.length, node = nodes[i]; i--;) { 
     node.style.backgroundColor = 'white'; 
    } 

    target.style.backgroundColor = 'red'; 
    return false; 
}; 

甚至?:

task.prototype.changeSize = function(e) { 
    var target = e.target, 
     nodes = e.target.parentNode.childNodes, 
     i = nodes.length, node; 

    for (node = nodes[i]; i-- && node.style.backgroundColor = 'white';); 

    return !(target.style.backgroundColor = 'red'); 
};