读书人

为何这个脚本只能执行一次

发布时间: 2012-10-18 13:46:55 作者: rapoo

为什么这个脚本只能执行一次

JScript code
<!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>

第一次点击链接#odiv的背景颜色可以改变,为什么以后的点击脚本不会执行呢

[解决办法]
因为第一次进去肯定不成立 就变成了 #000000
第二次进去还是不会成立因为 获取到的是 “none repeat scroll 0% 0% rbg(0,0,0,)”
样式属性不是你放进去什么值 获取出来就是什么值,它有它自己的一套解析方式。
所次 你每次点击 都会改变成 #000000 其实代码是一直执行的 只是没效果而已
[解决办法]
试试这个

HTML code
<!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语句判断试试
[解决办法]
JScript code
<!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> 

读书人网 >JavaScript

热点推荐