2012-12-21 5 views
-1

자바 스크립트에서 코드를 단순화 (또는 향상)하려고합니다. 내 코드는 흰색에 모든 <a> 링크의 배경색을 변경하고 선택 <a> 태그를 빨간색 배경을 줄 것이다 자바 스크립트 기능 코드 단순화

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

처럼

나는이

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입니다. 내가 필요한 것은 어울리지 만 내 changeSize 함수에서 더 예쁘다고 느낄 수 있습니다.

더 좋은 방법이 있나요? 고마워요!

+0

당신은 최대 귀여움을 위해 jQuery를 사용하여 생각 해 봤나? – 0x499602D2

+4

[function.bind]가 IE <9에서 작동하지 않는다는 것을 [codereview.se] –

+1

에 물어보십시오. –

답변

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