使用单个函数而不是多个函数的Javascript
代码如下:使用单个函数而不是多个函数的Javascript,javascript,function,Javascript,Function,代码如下: <script type="text/javascript"> function ChangeColor1() { t1.style.backgroundColor = 'pink'; t2.style.backgroundColor = ''; t3.style.backgroundColor = ''; } function ChangeColor2() { t1.style.backgro
<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>
函数ChangeColor1()
{
t1.style.backgroundColor=‘粉色’;
t2.style.backgroundColor='';
t3.style.backgroundColor='';
}
函数ChangeColor2()
{
t1.style.backgroundColor='';
t2.style.backgroundColor=‘粉色’;
t3.style.backgroundColor='';
}
函数ChangeColor3()
{
t1.style.backgroundColor='';
t2.style.backgroundColor='';
t3.style.backgroundColor=‘粉色’;
}
1.
2.
3.
4.
5.
6.
7.
8.
9
在该程序中,使用了3个函数。我想用一个函数而不是一个函数来完成这个任务
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' : '';
}
}
var ts=[t1,t2,t3];
函数更改颜色(n){
对于(变量i=0;i
或者您可以直接引用id:
function changeColor(n){
for (var i = 1; i < 4; i++){
document.getElementById('t'+i).style.backgroundColor = n == i ? 'pink' : '';
}
}
函数更改颜色(n){
对于(变量i=1;i<4;i++){
document.getElementById('t'+i).style.backgroundColor=n==i?'pink':'';
}
}
您还可以进一步引用行本身,而不是将索引指定为参数(保持通用):
函数更改颜色(t){
对于(变量n=1;n<4;n++){
var tn=document.getElementById('t'+n);
tn.style.backgroundColor=tn.id==t.id.“粉色”:“;
}
}
... onclick=“changeColor(this);”。。。
注意:并非所有浏览器都接受不带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":"";
}
}
函数更改颜色(行){
var idx=row.id;
对于(var i=1;i@mplungjan:巧合,不是故意的。但如果你愿意,我可以删除它们。我发布了我的初始解决方案,然后看到问题的重新格式,并在
中看到ID,并进行了其他更改。起初我没有在代码中捕获ID,但后来语法突出显示使其更可见。都德,这对我有用:)上帝保佑
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);">