为什么这个脚本只能执行一次
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>点击改变背景颜色</title><script language="javascript">function changecolor(){ x = document.getElementById("odiv"); x.style.background="#000000"?"#ffffff":"#000000";}</script><style type="text/css">*{ margin:0; padding:0;}#odiv{ width:100px; height:100px; background:#0F0; border:2px solid #000000;}</style></head><body><a href="#" onclick="changecolor()">链接</a><div id="odiv"></div></body></html><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>点击改变背景颜色</title><script language="javascript">function changecolor(){ x = document.getElementById("odiv"); alert(x.style.backgroundColor); x.style.backgroundColor = x.style.backgroundColor == "rgb(255, 255, 255)"?"#000000":"#ffffff";}</script><style type="text/css">*{ margin:0; padding:0;}#odiv{ width:100px; height:100px; background:#0F0; border:2px solid #000000;}</style></head><body><a href="#" onclick="changecolor()">链接</a><div id="odiv"></div></body></html>
[解决办法]
因为你页面加载出来的时候,div通过css样式document.getElementById("odiv")获得的是#0F0,而但你点击onclick的时候你用三元运算判断,为#000000匹配则显示#ffffff,不成立则显示#000000
你在控制颜色的变换时。再仔细看看。。用if语句判断试试
[解决办法]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset="utf-8" /><title>点击改变背景颜色</title><script language="javascript">function changecolor(){ x = document.getElementById("odiv"); x.style.backgroundColor=x.style.backgroundColor.toString()=="#000000"?"#ffffff":"#000000";}</script><style type="text/css">*{ margin:0; padding:0;}#odiv{ width:100px; height:100px; background:#000000; border:2px solid #000000;}</style></head><body><a href="#" onclick="changecolor()">链接</a><div id="odiv"></div></body></html>