我們都知道在IE中建立表單元素可以有三種方式var oInput = document.createElement("input");
var oInput = document.createElement("<input />");
var oInput = document.createElement("<input name='' />");
在Firefox裡面僅支援var oInput = document.createElement("input");
想要相容IE/Firefox動態建立radio button元素可以這樣寫:
function createRadio(name,id,value,isChecked)
{
var oRadio = null;
if(isIE)
{
oRadio = document.createElement("<input name='" + name + (isChecked ? "' checked='"+ isChecked +"'/>" : "' />"));
oRadio.id = id;
oRadio.type = "radio";
oRadio.value = value;
}
else
{
oRadio = document.createElement("input");
oRadio.setAttribute("type","radio");
oRadio.setAttribute("id",id);
oRadio.setAttribute("name",name);
oRadio.setAttribute("value",value);
if(isChecked)
{
oRadio.setAttribute("checked",isChecked);
}
}
return oRadio;
}
延伸一下,動態建立input任意元素程式碼片段如下即可:function createElement(tagName,name,type,value)
{
var element = null;
try
{
element = document.createElement('<'+tagName+' name="'+name+'" />');
element.type = type;
element.value = value;
}
catch (e)
{
}
if (!element)
{
element = document.createElement(tagName);
element.setAttribute("type",type);
element.setAttribute("name",name);
element.setAttribute("value",value);
}
return element;
}