示例代码: <body> <table border="1" cellspacing="0" cellpadding="0" id="apple" > <tbody> <tr> <td id="banana" style="color:red" >不吃苹果</td> </tr> </tbody> </table> </body> 尽量采用W3C DOM 的写法 以前访问对象可能是: document.all.apple 或者 apple 现在应该采用: document.getElementById("apple") 以ID来访问对象,且一个ID在页面中必须是唯一的 document.getElementsByTagName("div")[0] 以标签名来访问对象 原来设置对象的属性可能是: document.all.apple.width=100 或 apple.width=100 现在应该采用: document.getElementById("apple").setAttribute("width","100") document.getElementsByTagName("div")[0].setAttribute("width","100") 访问对象的属性则采用: document.getElementById("apple").getAttribute("width") document.getElementsByTagName("div")[0].getAttribute("width") W3C DOM在IE下的一些限制 因为起先的IE占据整个浏览器95%的份额,没有竞争压力,所以这位老大就硬是要玩点另类,不完全按WEB标准来搞。 在IE下不能正确使用setAttribute来设置对象的style、class以及事件响应属性, 因此我还得按原来的点记法来访问和设置,以达到兼容各种浏览器的效果,如: document.getElementById("banana").class document.getElementById("banana").style.color document.getElementById("banana").onclick document.getElementById("banana").class="fruit" document.getElementById("banana").style.color="blue" document.getElementById("banana").onclick= function (){alert("我是香蕉")} 关于Firefox下的onload问题 function over(){ alert("页面加载完毕") } 正常情况下,我们赋与onload响应函数是: document.body.onload= over 但是在Firefox下这样无法执行, 所以我们都都采用下面这种形式: window.onload=over 关于IE下TABLE无法插入新行的问题 IE下TABLE无论是用innerHTML还是appendChild插入<tr>都没有效果,而其他浏览器却显示正常。解决他的方法是,将<tr>加到TABLE的<tbody>元素中,如下面所示: var row = document.createElement("tr"); var cell = document.createElement("td"); var cell_text = document.createTextNode("香蕉不吃苹果"); cell.appendChild(cell_text); row.appendChild(cell); document.getElementsByTagName("tbody")[0].appendChild(row);
推荐阅读
javascript一些不错的函数脚本代码
计算字符长度的js函数复制代码 代码如下:function LEN(str){ var i,sum=0; for(i=0;i<str.length;i++){ if((str.charCodeAt(i)>=0) && (str.charCodeAt(i)<=255)) sum=sum+1; else sum=sum+2; } return sum; }去字>>>详细阅读
本文标题:Javascript多种浏览器兼容写法分析第1/3页
地址:http://www.17bianji.com/kaifa2/JS/29449.html
1/2 1