JavaScript 更改HTML标签的属性

使用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:想要改成的值

END

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值