使用setAttribute来更改属性值
实现
点击div之后,更改该div的背景色和文字,同时更改被点击时调用的js方法。
点击前
点击后
再次点击
完整代码
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
#god {
width:150px;
height:50px;
color:#FFF;
line-height:50px;
text-align:center;
border-radius:15px;
background-color:#0C6;
margin-left:auto;
margin-right:auto;
}
</style>
<script type="text/javascript">
function changeColor() {
//获取god
var myGod = document.getElementById("god");
//更换god的文本内容
myGod.firstChild.nodeValue = "再点看看?";
//更换god的背景颜色
myGod.style.backgroundColor = "red";
//本次重点,setAttribute;
//设置标签属性的值。该标签拥有的任何属性都可以设置
//例如 a标签有href属性,也可以通过这个来改变
//这里是替换了点击god时调用的js方法,本来是调用changeColor()的
//通过setAttribute换成了what_the_fuck()方法
myGod.setAttribute("onclick", "what_the_fuck()");
}
function what_the_fuck() {
//弹窗
alert("My god! 你点我干嘛!我要让你变回去");
//获取god
var restore = document.getElementById("god");
//设置god的背景色
restore.style.backgroundColor = "#0C6";
//替换god的文本
restore.firstChild.nodeValue = "点我!点我!";
//替换点击时,调用的js方法
restore.setAttribute("onclick", "changeColor()");
}
</script>
</head>
<body bgcolor="#333333">
<div id="god" onclick="changeColor()">
点我!点我!
</div>
<hr width="80%" color="#FFFFFF" />
</body>
</html>
思路
大概是点击god之后
更改了它的onclick值,使其下次被点击时调用另一个方法
更改了它的背景颜色
更改了它的文字
然后再次点击是,调用了另外一个方法,所以会弹窗
同时再次的
更改了它的onclick值,使其下次被点击时调用另一个方法
更改了它的背景颜色
更改了它的文字
使其复原
关键代码
myGod.setAttribute("onclick", "what_the_fuck()");
这里的setAttribute方法更改了【god】div的onclick属性值
原来god是这样的
<div id="god" onclick="changeColor()">点我!点我!</div>
使用了
myGod.setAttribute("onclick", "what_the_fuck()");
之后,那么它的onclick值就改变了。
<div id="god" onclick="what_the_fuck()">点我!点我!</div>
div里面还有一个align属性对吧,所以也可以这样
myGod.setAttribute("align", "center");
此时的god是
<div id="god" onclick="what_the_fuck()" align="center">点我!点我!</div>
所以setAttribute的使用还是很简单的。
setAttribute(参数1, 参数2)
参数1:html标签的某个属性的名称,如id、onclick、class
参数2:想要改成的值