1

这里的代码:

 <script type="text/javascript">

   function ChangeColor1()
   {
    t1.style.backgroundColor = 'pink';
    t2.style.backgroundColor = '';
    t3.style.backgroundColor = '';

   }


    function ChangeColor2()
    {

    t1.style.backgroundColor = '';  
    t2.style.backgroundColor = 'pink';
    t3.style.backgroundColor = '';

    }


    function ChangeColor3()
    {

    t1.style.backgroundColor = '';
    t2.style.backgroundColor = '';
    t3.style.backgroundColor = 'pink';

        }
        </script>

        </head>
        <body>

        <table width="50%" border="1" >

        <tr id="t1" onclick="ChangeColor1();">
        <td>1</td>
        <td>2</td>
        <td>3</td>
        </tr>

        <tr id="t2" onclick="ChangeColor2();">
    <td>4</td>
    <td>5</td>
    <td>6</td>
    </tr>

     <tr id="t3" onclick="ChangeColor3();">
    <td>7</td>
    <td>8</td>
    <td>9</td>
    </tr>
    </table>
    </body>

在这个程序中使用了 3 个函数。我想使用一个函数而不是一个函数来完成这项任务。

4

2 回答 2

2
function changeColor(n){
  t1.style.backgroundColor = n == 1 ? 'pink' : '';
  t2.style.backgroundColor = n == 2 ? 'pink' : '';
  t3.style.backgroundColor = n == 3 ? 'pink' : '';
}

... onclick="changeColor(1)" ...

将是我将如何重构它。var ts = [t1,t2,t3]或者更好的是制作一个then 引用的数组ts[n]

var ts = [t1,t2,t3];
function changeColor(n){
  for (var i = 0; i < ts.length; i++){
    ts[i].style.backgroundColor = (i+1) == n ? 'pink' : '';
  }
}

或者你可以直接引用id:

function changeColor(n){
  for (var i = 1; i < 4; i++){
    document.getElementById('t'+i).style.backgroundColor = n == i ? 'pink' : '';
  }
}

您还可以更进一步并引用行本身,而不是将索引指定为参数(保持通用):

function changeColor(t){
  for (var n = 1; n < 4; n++){
    var tn = document.getElementById('t'+n);
    tn.style.backgroundColor = tn.id == t.id ? 'pink' : '';
  }
}

... onclick="changeColor(this);" ...
于 2012-09-13T14:34:53.407 回答
1

演示

注意:并非所有浏览器都会接受没有 document.getElementById 的 t1.style

function ChangeColor(row) {
  var idx=row.id;
  for (var i=1;i<=3;i++) {
    document.getElementById("t"+i).style.backgroundColor = (idx==="t"+i)?"pink":""; 
  }
}

使用

<tr id="t1" onclick="ChangeColor(this);">
<tr id="t2" onclick="ChangeColor(this);">
<tr id="t3" onclick="ChangeColor(this);">
于 2012-09-13T14:34:57.157 回答