更改按钮颜色的onClick [英] Change Button color onClick
问题描述
我希望我的按钮
来我点击它每一次改变颜色。但它只会改变在第一次点击的颜色。
我相信这个问题是在的setColor
功能。我每次点击按钮
,计数
被设置为1,所以,即使当我把它设置为0,它被重置为1在下一次点击。我该如何解决这个问题?有没有在JavaScript / HTML全局变量,但这样做很容易得到解决?
<!DOCTYPE HTML>
< HTML和GT;
< HEAD><脚本>
功能的setColor(BTN,颜色){
变种数= 1;
VAR财产=的document.getElementById(BTN);
如果(计数== 0){
property.style.backgroundColor =#FFFFFF
数= 1;
}
其他{
property.style.backgroundColor =#7FFF00
计数= 0;
}}
< / SCRIPT>
< /头><身体GT;<输入类型=按钮ID =按钮值=button风格=颜色:白的onclick =的setColor('按钮','#101010'); />< /身体GT;
< / HTML>
有的确是在JavaScript中的全局变量。您可以了解更多关于<一个href=\"http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript\">scopes,这是在这种情况下有所帮助。
您code可能是这样的:
&LT;脚本&GT;
变种数= 1;
功能的setColor(BTN,颜色){
VAR财产=的document.getElementById(BTN);
如果(计数== 0){
property.style.backgroundColor =#FFFFFF
数= 1;
}
其他{
property.style.backgroundColor =#7FFF00
计数= 0;
}
}
&LT; / SCRIPT&GT;
希望这有助于。
I want my Button
to change color every time I click on it. But it only changes color on the first click.
I believe the problem is in the setColor
function. Every time I click on the Button
, count
gets set to 1. So even when I set it to 0, it gets reset to 1 on the next click. How do I fix this? Are there global variables in javascript/html where this would easily be solved?
<!DOCTYPE html>
<html>
<head>
<script>
function setColor(btn, color){
var count=1;
var property = document.getElementById(btn);
if (count == 0){
property.style.backgroundColor = "#FFFFFF"
count=1;
}
else{
property.style.backgroundColor = "#7FFF00"
count=0;
}
}
</script>
</head>
<body>
<input type="button" id="button" value = "button" style= "color:white" onclick="setColor('button', '#101010')";/>
</body>
</html>
There are indeed global variables in javascript. You can learn more about scopes, which are helpful in this situation.
Your code could look like this:
<script>
var count = 1;
function setColor(btn, color) {
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "#FFFFFF"
count = 1;
}
else {
property.style.backgroundColor = "#7FFF00"
count = 0;
}
}
</script>
Hope this helps.
这篇关于更改按钮颜色的onClick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!