封装一些常用JavaScript方法(下)
上篇在这里:一些封装好的常用JavaScript方法(上)
- 封装原生js的 Ajax
function ajax(method, url, callback, data, flag) {
var xhr;
flag = flag || true;
method = method.toUpperCase();
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHttp');
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
}
if (method == 'GET') {
var date = new Date(),
timer = date.getTime();
xhr.open('GET', url + '?' + data + '&timer' + timer, flag);
xhr.send()
} else if (method == 'POST') {
xhr.open('POST', url, flag);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(data);
}
}
- 封装 filter 方法
Array.prototype.myFilter = function (func, obj) {
var len = this.length;
var arr = [];
var _this = arguments[1] || window;
for (var i = 0; i < len; i++) {
func.call(_this, this[i], i, this) && arr.push(this[i]);
}
return arr;
}
- 封装 forEach 方法
Array.prototype.myForEach = function (func, obj) {
var len = this.length;
var _this = arguments[1] ? arguments[1] : window;
for (var i = 0; i < len; i++) {
func.call(_this, this[i], i, this)
}
}
- 绑定事件的兼容性写法
function addEvent(element, type, handle) {
if (element.addEventListener) { // 普通浏览器和 ie9 以上
element.addEventListener(type, handle, false);
} else if (element.attachEvent) { // ie6 - ie8
element.attachEvent('on' + type, function () {
handle.call(element);
})
} else {
element['on' + type] = handle;
}
}
- 获取视口的尺寸
function getViews() {
if (window.innerWidth) {
return {
w: window.innerWidth,
h: window.innerHeight
}
} else {
// ie8 及以下
if (document.compatMode === "BackCompat") {
// 怪异模式
return {
w: document.body.clientWidth,
h: document.body.clientHeight
}
} else {
// 标准模式
return {
w: document.documentElement.clientWidth,
h: document.documentElement.clientHeight
}
}
}
}
这里是万物之恋,我们下次再见了!