简单的日期选择器
此段代码中值得注意的地方:
1. 兼容事件监听处理
var Event = function() { this.addEvent = function(type, handler, capture){ if(this.addEventListener){ this.addEventListener(type, handler, capture); }else if(this.attachEvent){ this.attachEvent("on" + type, handler); } }; this.detachEvent = function(type, handler, capture){ if(this.removeEventListener){ this.removeEventListener(type, handler, capture); }else if(this.detachEvent){ this.detachEvent("on" + type, handler); } }; };
2. 判断父元素是否存在
判断parents是否存在值且其属于元素(nodeType == 1)
if(parents && parents.nodeType == 1){ _p = parents; }else{ _p = document.getElementsByTagName("body")[0]; }
3. table在IE下无法使用innerHTML属性
需要使用到
//创建table下的两个子节点 this.thead = document.createElement("thead"); this.tbody = document.createElement("tbody"); //创建thead的内容 var tr = document.createElement("tr"); for(var h = 0; h < this.dateWeek.length; h++){ var th = document.createElement("th"); var text = document.createTextNode("text"); text.nodeValue = this.dateWeek[h]; th.appendChild(text); tr.appendChild(th); } this.thead.appendChild(tr); //将thead tbody加入到table中 this.calBody.appendChild(this.thead); this.calBody.appendChild(this.tbody); //创建tbody this.createTableBody();
有个简便方法,将table所有代码拼接成字符串,放入一个div的innerHTML中。
同样可以达成这样的效果。
4. 清空tbody
//empty the body if it has childNode while(this.tbody.children.length) { this.tbody.deleteRow(); }
5. 兼容获得事件对象
//获取事件对象 var target = window.event.srcElement || evt.target; //获取对象的tagName var tagName = window.event.srcElement.tagName || evt.target.nodeName;
----- 但愿人长久,千里共婵娟
(如果你对本篇博文有任何问题和赞同,请回复告诉我)