2012-09-13 31 views
1

這裏的代碼:Javascript的使用單一功能而不是多個

<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種功能。我想用一個函數來完成這個任務,而不是一個。

回答

1

DEMO

注:並非所有的瀏覽器中使用

<tr id="t1" onclick="ChangeColor(this);"> 
<tr id="t2" onclick="ChangeColor(this);"> 
<tr id="t3" onclick="ChangeColor(this);"> 
+1

老兄,它爲我:) :)上帝保佑 –

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]然後參考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);" ... 
+0

@mplungjan將接受t1.style沒有的document.getElementById

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

:機緣巧合,不是故意的。但如果您願意,我可以將其刪除。我發佈了我的初始解決方案,然後看到了問題的重新格式,並在''中看到了ID並做了其他更改。在第一遍時,我沒有在代碼中捕捉到ID,但是語法突出顯示使其更加醒目。 –

相關問題