javascript动态创建radio button元素支持IE/Firefox
我们都知道在IE中创建表单元素可以有三种方式
想要兼容IE/Firefox动态创建radio button元素可以这样写:
var oInput = document.createElement("input");
var oInput = document.createElement("<input />");
var oInput = document.createElement("<input name='' />");
在Firefox里面仅支持var oInput = document.createElement("<input />");
var oInput = document.createElement("<input name='' />");
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任意元素代码片段如下即可:{
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;
}
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;
}
{
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;
}