javascript动态创建radio button元素支持IE/Firefox

    我们都知道在IE中创建表单元素可以有三种方式
None.gif var  oInput  =  document.createElement( " input " );
None.gif
var  oInput  =  document.createElement( " <input /> " );
None.gif
var  oInput  =  document.createElement( " <input name='' /> " );
    在Firefox里面仅支持
None.gif var  oInput  =  document.createElement( " input " );

    想要兼容IE/Firefox动态创建radio button元素可以这样写:

None.gif function  createRadio(name,id,value,isChecked)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
var oRadio = null;
InBlock.gif    
if(isIE)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        oRadio 
= document.createElement("<input name='" + name + (isChecked ? "' checked='"+ isChecked +"'/>" : "' />"));
InBlock.gif        oRadio.id 
= id;
InBlock.gif        oRadio.type 
= "radio";
InBlock.gif        oRadio.value 
= value;
ExpandedSubBlockEnd.gif    }

InBlock.gif    
else
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        oRadio 
= document.createElement("input");
InBlock.gif        oRadio.setAttribute(
"type","radio");
InBlock.gif        oRadio.setAttribute(
"id",id);
InBlock.gif        oRadio.setAttribute(
"name",name);
InBlock.gif        oRadio.setAttribute(
"value",value);
InBlock.gif        
if(isChecked)
ExpandedSubBlockStart.gifContractedSubBlock.gif       
dot.gif{
InBlock.gif            oRadio.setAttribute(
"checked",isChecked);
ExpandedSubBlockEnd.gif        }
        
ExpandedSubBlockEnd.gif    }

InBlock.gif    
return oRadio;
ExpandedBlockEnd.gif}
    延伸一下,动态创建input任意元素代码片段如下即可:
None.gif function  createElement(tagName,name,type,value)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
var element = null;
InBlock.gif    
try 
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        element 
= document.createElement('<'+tagName+' name="'+name+'" />');
InBlock.gif        element.type 
= type;
InBlock.gif        element.value 
= value;
ExpandedSubBlockEnd.gif    }

InBlock.gif    
catch (e)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
ExpandedSubBlockEnd.gif    }

InBlock.gif    
if (!element)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        element 
= document.createElement(tagName);
InBlock.gif        element.setAttribute(
"type",type);
InBlock.gif        element.setAttribute(
"name",name);
InBlock.gif        element.setAttribute(
"value",value);
ExpandedSubBlockEnd.gif   }

InBlock.gif   
return element;
ExpandedBlockEnd.gif}
 

转载于:https://www.cnblogs.com/BeanHsiang/archive/2008/01/08/1030512.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值