IE和Firefox都兼容的document.createElement方法实现

本文介绍如何使用JavaScript动态创建HTML元素,并演示了不同浏览器兼容性的解决方案。此外,还详细说明了如何为这些元素绑定点击事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



[JScript]  view plain copy
  1. var content = document.getElementById("content");  
  2. var text = document.createElement("input");  
  3. text.type="text";  
  4. text.id="name";  
  5. content.appendChild(text);  
把一个事件赋给这个这个对象的onclick的方法如下:
假设fun1是方法名
[JScript]  view plain copy
  1. text.onclick=fun1;  
[JScript]  view plain copy
  1. text.onclick=new   Function(fun1(obj1,obj2));    
[JScript]  view plain copy
  1. text.attachEvent("onclick",fun1);  

createElement()兼容火狐,chrome浏览器的定法:

Code:
  1. var e = document.createElement("div");   
  2. e.id = "testE";   
  3. e.className = "testClass";   
  4. e.style.width ="300px";   
  5. e.style.height = "300px";   
  6. e.style.border = "#ff6600 solid 1px";   
  7. e.style.background = "#dedede";  

返回对象document.createElement("div")

function $ce(str){
        if (document.all) return document.createElement(str);
        str = trim(trim(str).replace(/^<|\/?\s*>$/g,""));
        var a = str.split(/\s+/);
        var o = document.createElement(a[0]);
        if (a.length>1)
        {
                str.replace(/(\w+)=([^\s\'\"]+)|(\w+)=\'([^\']+)\'|(\w+)=\"([^\"]+)\"/g,function(v,v1,v2,v3,v4,v5,v6)
                {
                        o.setAttribute(v1||v3||v5,v2||v4||v6);
                });
        }
        return o;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值