开发跨浏览器JavaScript的几点注意事项
本文是《Ajax基础教程》的笔记整理。
- 向表中添加行
<table id="myTable" border="0"> <tbody id="myTableBody"></tbody></table>
对于主流浏览器,可以使用appendChild方法,将创建的单元格添加到表行中,再把表行添加到表中。
但是在IE中,这样做不会将表行添加到表中,并且不会抛出任何错误。解决方法很简单,将行增加到表体(tbody)而不是表格。
后面一种方法并不只针对IE,在所以主流浏览器上都能用。 - 通过JavaScript设置元素的样式
主流浏览器中:var spanElement = document.getElementById("mySpan"); spanElement.setAttribute("style","color:red;");针对IE(此方法对除Opera外的主流浏览器都适用):
spanElement.style.cssText = "color:red;";
所以,为了让代码在所有当前主流浏览器上都可移植,需要同时使用这两种方法:
var spanElement = document.getElementById("mySpan"); spanElement.setAttribute("style","color:red;"); spanElement.style.cssText = "color:red;"; - 设置元素的class属性
在脚本中动态的为某一元素设置css类属性,等同于class=”"
主流浏览器中:var element = document.getElementById("myElement"); element.setAttribute("class","styleClass");针对IE:
var element = document.getElementById("myElement"); element.setAttribute("className","styleClass");没办法,IE就是这么恶心,当前大多数浏览器都会使用class属性名而忽略className,IE正好相反。
- 创建输入元素
HTML本身有一组有限的输入元素,包括单行文本框、多行文本框、选择框、按钮、单选按钮等。有时我们需要用JavaScript动态的创建这些输入元素。
对于单行文本框、按钮、复选框、单选按钮来说,它们都有同样的元素名input,只是type属性的值不同。需要注意的是document.createElement和setAttribute两句的顺序,只有创建了元素,而且正确设置了type属性时,才会把新创建的元素增加到其父元素中。var button = document.createElement("input"); button.setAttribute("type","button"); document.getElementById("formElement").appendChild(button); - 向输入元素增加事件处理程序
主流浏览器:var formElement = getElementById("formElement"); formElement.setAttribute("onclick","doSomething();");针对IE:
var formElement = getElementById("formElement"); formElement.onclick = function(){dosomething();};幸运的是,后面这种方法得到了IE和所有其他主流浏览器的主持。
- 创建单选按钮
主流浏览器:var radioButton = document.createElement("input"); radioButton.setAttribute("type","radio"); radioButton.setAttribute("name","radioButton"); radioButton.setAttribute("value","checked");针对IE:
var radioButton = document.createElement("<input type='radio' name='radioButton' value='checked' />");可以看出,在IE中,创建单选按钮的方法与其他浏览器所用的方法完全不同,而且根本不兼容。
为了方便,我们需要“浏览器嗅探(browser-sniffing)机制”。IE能识别出名为uniqueID的document对象的专用属性,名为uniqueID。所用可以利用其来判断脚本是不是在IE中运行。
上面的代码的跨浏览器版本:If(document.uniqueID) { //IE var radioButton = document.createElement("<input type='radio' name='radioButton' value='checked' />"); } Else { //标准浏览器 var radioButton = document.createElement("input"); radioButton.setAttribute("type", "radio"); radioButton.setAttribute("name", "radioButton"); radioButton.setAttribute("value", "checked"); }