-1

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 関数でよりきれいになることができると感じました.

より良い書き方はありますか?どうもありがとう!

4

1 に答える 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');
};
于 2012-12-21T23:02:17.087 に答える