事件封装
事件绑定封装
function addEvent(elem,type,handle){
if(elem.addEventListener){
elem.addEventListener(type,handle,false);
}else if(elem.attachEvent){
elem.attachEvent(on+type,function(){
handle.call(elem);
})
}else{
elem['on' +type] = handle;
}
}
阻止事件冒泡封装
function stopBubble(event){
if(event.stopPropagation){
event.stopPropagation();
}else{
event.cancleBubble = true;
}
}
异步加载事件封装
function loadScript(url,callback){
var script = document.createElement('script');
script.type = 'text/javascript';
if(script.readyState){
script.onreadystatechange = function(){//IE
if(script.readyState == 'loaded' || script.readyState == 'complete'){
callback();
}
}
}else{
script.onload = function(){//opera safari chrome firefox 等适用
callback();
}
}
script.src = url;//先绑定再下载
document.head.appendChild(script);
}
//注意引用时要这样做
loadScript('demo.js',function(){
test();
})
Ajax-GET和POST方法封装
function obj2str(data){
var res = [];
data.t = new Date().getTime();
for(var key in data){
//将中文转换为特殊字符串,例如%E5%BC%A0%E4%BD%86
res.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
return res.join('&');
}
function ajax(option){//timeout为超时时间
//0.将对象转换为字符串
var str = obj2str(option.data);//转发为key=value&key=value这种形式
//1.创建一个异步对象
var xmlhttp,timer;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP')
}
//2.设置请求方式和请求地址
if(option.type.toLowerCase() === 'get'){
xmlhttp.open(option.type,option.url+'?='+ str,true);
//3.发送请求
xmlhttp.send();
}else{
xmlhttp.open(option.type,option.url,true);
//以下代码只能写到open和send之间
xmlhttp.setRequestHeader('content-type','application/x-www-form-urlencoded');
xmlhttp.send(str);
}
//4.监听状态的变化
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4){
//如果接受到服务器的响应,就要把定时器关掉
clearInterval(timer);
if(xmlhttp.status >=200 && xmlhttp.status <= 300 || xmlhttp.status == 304){
//状态码判断
//成功后执行的回调函数
option.success(xmlhttp);
}else{
//失败后执行的回调函数
option.error(xmlhttp);
}
}
}
//判断外界是否传入了超时时间
if(option.timeout){
timer = setTimeout(function(){
xmlhttp.abort();//中断请求
clearInterval(timer);
},option.timeout)
}
}