使用setAttribute()改变网页中标签的onclick属性

本文探讨了在JavaScript中使用setAttribute()方法为元素动态添加事件监听器时遇到的浏览器兼容性问题,并提供了适用于不同浏览器(包括IE)的解决方案。
2、setAttribute()的差异我们经常需要在JavaScript中给Element动态添加各种属性,这可以通过使用setAttribute()来实现,这就涉及到了浏览器的兼容性问题。
var bar = document.getElementById("foo");
bar.setAttribute("onclick", "javascript:alert('This is a test!');");
这里利用setAttribute指定e的onclick属性,简单,很好理解。
但是IE不支持,IE并不是不支持setAttribute这个函数,而是不支持用setAttribute设置某些属性,例如对象属性、集合属性、事件属性,也就是说用setAttribute设置style和onclick这些属性在IE中是行不通的。
为达到兼容各种浏览器的效果,可以用点符号法来设置Element的对象属性、集合属性和事件属性。document.getElementById("foo").onclick= function () { alert("This is a test!"); }

<!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>
    
<title>无标题页</title>
    
<script type="text/javascript">
    
function cancleEvent()
    
{
    document.getElementById(
'a').setAttribute("onclick",'');
    document.getElementById(
'g').innerHTML="取消事件!";
    }

    
function setEvent()
    
{

    document.getElementById(
'a').setAttribute("onclick",'alert("你好!")');//firefox
    
    document.getElementById(
'a').onclick= function () { alert("This is a test!"); }//IE firefox也有作用,但是使用firebug调试看不到修改后的效果,使用上面的方法可以看到。
    
    document.getElementById(
'Div1').innerHTML="设置事件!";
    }

    
</script>
</head>
<body>
    
<div style="width: 791px; height: 100px">
        
<div id="a" name="a" style="width: 108px; height: 30px; background-color: #ffccff" onclick="alert('你好!');">
    
</div>
    
&nbsp;
    
<div id="g" style="width: 361px; height: 58px; background-color: #00ff00" onclick="cancleEvent();">取消
    
</div>
    
<br />
    
<div id="Div1" style="width: 361px; height: 58px; background-color: #00ff00" onclick="setEvent();">设置
    
</div>

</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值