2012-12-21 76 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'); 
};