将Css应用于Javascript中的当前按钮单击

将Css应用于Javascript中的当前按钮单击,javascript,Javascript,我需要使用Javascript更改三个按钮的背景色。代码如下: <input type="button" id="btn" value="Box 1" onclick="changeColor(this)"> <input type="button" id="btn" value="Box 2" onclick="changeColor(this)"> <input type="button" id="btn" value="Box 3" onclick="chan

我需要使用Javascript更改三个按钮的背景色。代码如下:

<input type="button" id="btn" value="Box 1" onclick="changeColor(this)">
<input type="button" id="btn" value="Box 2" onclick="changeColor(this)">
<input type="button" id="btn" value="Box 3" onclick="changeColor(this)">

<script>
    function changeColor(this) {
        this.document.getElementById("btn").style.backgroundColor = "red";
    }
</script>

函数changeColor(此){
this.document.getElementById(“btn”).style.backgroundColor=“红色”;
}
它适用于第一个按钮(框1)

当我单击第二个和第三个按钮时,第一个按钮的背景色会改变

但是我需要更改我单击的各个按钮的背景色


有谁能帮我知道我错在哪里吗?

使用
this
作为变量名会导致Javascript错误,因为
this
是保留关键字。将
this
更改为按钮变量(
element
,在下面的代码段中),并将其传递给函数

另外-永远不要为多个元素设置相同的ID这将呈现为无效HTML文档

下面是一段有效的代码片段:


功能更改颜色(元素){
element.style.backgroundColor=“红色”;
}

问题是您对所有按钮使用相同的
id
。改用
class

另外,
是一个保留关键字,因为您将其用作参数名会导致错误

函数更改颜色(elem){
elem.style.backgroundColor=“红色”;
}

您应该将
id
更改为
class
,因为
id
必须是唯一的

试着这样做:

<input type="button" class="btn" value="Box 1" onclick="changeColor(this)">
<input type="button" class="btn" value="Box 2" onclick="changeColor(this)">
<input type="button" class="btn" value="Box 3" onclick="changeColor(this)">

<script>
    function changeColor(this) {
        element.style.backgroundColor = "red";
    }
</script>

函数changeColor(此){
element.style.backgroundColor=“红色”;
}

替换为您的参数,随您所需。因为
这是一个表示上下文的关键字。这里是
窗口
对象

function changeColor(element) {
   element.style.backgroundColor = "red";
}

id
在函数
changeColor
中也必须是唯一的,这可能与参数无关,您可以提供任何其他名称。在函数中,参数
elem
将表示触发单击事件的上下文。 从中删除id并更改其样式

函数更改颜色(elem){
this.document.getElementById(elem.id).style.backgroundColor=“red”;
}

您的函数始终使用
btn
id
引用元素,这三个输入都有

如果要将
(此)
传递到函数中,则应传递按钮的id

在函数中,您可以引用传入的id:

函数更改颜色(id){
document.getElementById(id).style.backgroundColor=“红色”;

}
这里是一个包含两种不同解决方案的工作片段,一种是您想要实现的解决方案,另一种是更好的解决方案,我建议您不要使用内联Javascript:
(请参见我的代码中的注释)

函数changeColor(elm){//“this”是保留关键字,更改为“elm”
elm.style.backgroundColor=“red”//这里不需要getElement,我们已经有了它,它是“elm”
}
//更好的解决方案:如果不使用内联JS,请执行以下操作:
var btns=document.getElementsByClassName(“btn”);
对于(变量i=0;i


具有多个具有相同ID的元素是无效的HTML。你应该把它修好。很高兴听到它对你有帮助。记下这一点,继续前进!;)