跨浏览器javascript的使用(动态的更新页面内容)
本文只是提供了一些常见情况
1 向表中追加行
<table id="myTableBody">
<tbody id="myTableBody"></tbody>
</table>
正确的做法是把行增加到表体,而不是增加到表
var cell = decument.createElement("td").appendChild(document.createTextNode("foo"));
var row = document.createElement("tr").appendChild(cell);
document.getElementById("myTableBody").appendChild(row);
2 设置元素的样式
非ie的做法
var spanElement = document.getElementById("mySpan");
spanElement.serAttribute("style", "font-weight:bold; color:red;");
ie的做法
var spanElement = document.getElementById("mySpan");
spanElement.style.cssText = "font-weight:bold; color:red;";
兼容的做法
var spanElement = document.getElementById("mySpan");
spanElement.serAttribute("style", "font-weight:bold; color:red;");
spanElement.style.cssText = "font-weight:bold; color:red;";
3 设置元素的class属性
非ie做法
var element = document.getElementById("myElement");
element.setAttribute("class", "styleClass");
ie的做法,使用setAttribute方法时ie识别className属性
element.setAttribute("className", "styleClass");
兼容的做法
var element = document.getElementById("myElement");
element.setAttribute("class", "styleClass");
element.setAttribute("className", "styleClass");
4 创建输入元素
先创建输入元素,再创建各属性特别是type属性,最后把它加到父元素中
var button = document.createElement("input");
button.setAttribute("type", "button");
document.getElementById("formElement").appendChild(button);
5 向输入元素增加事件处理程序
非ie做法
var formElement = document.getElementById("formElement");
formElement.setAttribute("onclick", "doFoo()");
兼容的做法
var formElement = document.getElementById("formElement");
formElement.onclick = function(){ doFoo(); };
6 创建单选按钮
非ie做法
var radioButton = document.createElement("input");
radioButton.setAttribute("type", "radio");
radioButton.setAttribute("name", "radioButton");
radioButton.setAttribute("value", "checked");
ie的做法
var radipButton = document.createElement("<input type='radio' name='radioButton' value='checked'>");
采用选择机制,ie能识别出名为uniqueID的document对象的专用属性,ie是唯一能识别出这个属性的浏览器
if (document.uniqueID)
{
//Internet Explorer
var radipButton = document.createElement("<input type='radio' name='radioButton' value='checked'>");
}
else
{
//Standards Compliant
var radioButton = document.createElement("input");
radioButton.setAttribute("type", "radio");
radioButton.setAttribute("name", "radioButton");
radioButton.setAttribute("value", "checked");
}