JavaScript 常用函數庫詳解

來源:互聯網
上載者:User

為此,收集了自己平時常用到一些JavaScript函數,它們在其它的JS庫也常見,現在整理並附上注釋,方便查閱,希望對大家有所協助。
注:假設以下所有函數都放在一個CC對象中,方便引用。 複製代碼 代碼如下://這個方法相信是最常用的了,
//它雖然沒有選取器那麼強大,但也有個小增強版,可查指定結點下ID所在的子項目
function $(id, p) {
//id是否是字串,還是一個HTML結點
var iss = id instanceof String || typeof id == "string";
if (iss && !p)
return document.getElementById(id);
//如果是結點的話就直接返回該結點
if(!iss)
return id;
//如果id與p是同一個元素,直接返回
if(p.id == id)
return p;
//往父結點搜尋
var child = p.firstChild;
while (child) {
if (child.id == id)
return child;
//遞迴搜尋
var v = this.$(id, child);
if (v)
return v;
child = child.nextSibling;
}
//的確找不到就返回null
return null;
}

複製代碼 代碼如下:each: function(object, callback, args) {
if (!object) {
return object;
}
if (args) {
if (object.length === undefined) {
for (var name in object)
if (callback.apply(object[name], args) === false) break;
} else for (var i = 0, length = object.length; i < length; i++)
if (callback.apply(object[i], args) === false) break;
} else {
if (object.length == undefined) {
for (var name in object)
if (callback.call(object[name], name, object[name]) === false) break;
} else for (var i = 0, length = object.length, value = object[0];
i < length && callback.call(value, i, value) !== false;
value = object[++i]) {}
}
return object;
}

複製代碼 代碼如下://數組
function isArray(obj) {
return (typeof obj === "array" || obj instanceof Array);
},
//字串
function isString(obj) {
return (typeof obj === "string" || obj instanceof String);
},
//函數
function isFunction(obj) {
return (typeof obj === "function" || obj instanceof Function);
},
//數字類型
function isNumber(ob) {
return (typeof ob === "number" || ob instanceof Number );
}

複製代碼 代碼如下:// 返回表單可提交元素的提交字串.
// 例如
// <form>
// <input type="text" name="user" value="rock" />
// <input type="text" name="password" value="123" />
// </form>
// 調用後就返回 user=rock&password=123
// 這些資料已經過encodeURIComponent處理,對非英文字元友好.
// form元素中如果沒有name,則以id作為提供字元名.
function formQuery(f){
// f,一個Form表單.
var formData = "", elem = "", f = CC.$(f);
var elements = f.elements;
var length = elements.length;
for (var s = 0; s < length; ++s) {
elem = elements[s];
if (elem.tagName == 'INPUT') {
if ( (elem.type == 'radio' || elem.type == 'checkbox') && !elem.checked) {
continue;
}
}
if (formData != "") {
formData += "&";
}
formData += encodeURIComponent(elem.name||elem.id) + "="
+ encodeURIComponent(elem.value);
}
return formData;
}

複製代碼 代碼如下:/**
* 移除數組指定元素.
* 參數既可傳遞一個整形下標,也可傳遞一個數組資料.
*/
Array.prototype.remove = (function(p) {
//參數為下標
if (CC.isNumber(p)) {
if (p < 0 || p >= this.length) {
throw "Index Of Bounds:" + this.length + "," + p;
}
this.splice(p, 1)[0];
return this.length;
}
//參數為數組資料,最終要找到下標來操作
if (this.length > 0 && this[this.length - 1] == p) {
this.pop();
} else {
var pos = this.indexOf(p);
if (pos != -1) {
this.splice(pos, 1)[0];
}
}
return this.length;
});

複製代碼 代碼如下:Array.prototype.indexOf = (function(obj) {
for (var i = 0, length = this.length; i < length; i++) {
if (this[i] == obj) return i;
}
return - 1;
});

複製代碼 代碼如下:/**
* 萬能而簡單的表單驗證函式,這個函數利用了JS動態語言特性,看上去很神秘,
* 實際是很形象的,查看個例子就清楚了.
*/
validate: function() {
var args = CC.$A(arguments),
form = null;
//form如果不為空白元素,應置於第一個參數中.
if (!CC.isArray(args[0])) {
form = CC.$(args[0]);
args.remove(0);
}
//如果存在設定項,應置於最後一個參數中.
//cfg.queryString = true|false;
//cfg.callback = function
//cfg.ignoreNull
//nofocus:true|false
var b = CC.isArray(b) ? {}: args.pop(),
d;
var queryStr = b.queryString,
ignoreNull = b.ignoreNull,
cb = b.callback;
var result = queryStr ? '': {};
CC.each(args,
function(i, v) {
//如果在fomr中不存在該name元素,就當id來獲得
var obj = v[0].tagName ? v[0] : form ? form[v[0]] : CC.$(v[0]);
//console.debug('checking field:',v, 'current value:'+obj.value);
var value = obj.value,
msg = v[1],
d = CC.isFunction(v[2]) ? v[3] : v[2];
//選項
if (!d || typeof d != 'object') d = b;
//是否忽略空
if (!d.ignoreNull && (value == '' || value == null)) {
//如果不存在回呼函數,就調用alert來顯示錯誤資訊
if (!d.callback) CC.alert(msg, obj, form);
//如果存在回調,注意傳遞的三個參數
//msg:訊息,obj:該結點,form:對應的表單,如果存在的話
else d.callback(msg, obj, form);
//出錯後是否聚集
if (!d.nofocus) obj.focus();
result = false;
return false;
}
//自訂驗證方法
if (CC.isFunction(v[2])) {
var ret = v[2](value, obj, form);
var pass = (ret !== false);
if (CC.isString(ret)) {
msg = ret;
pass = false;
}
if (!pass) {
if (!d.callback) CC.alert(msg, obj, form);
//同上
else d.callback(msg, obj, form);
if (!d.nofocus) obj.focus();
result = false;
return false;
}
}
//如果不設定queryString並通過驗證,不存在form,就返回一個對象,
//該對象包含形如{elementName|elementId:value}的資料.
if (queryStr && !form) {
result += (result == '') ?
((typeof obj.name == 'undefined' || obj.name == '') ? obj.id: obj.name) +
'=' + value: '&' + v[0] + '=' + value;
} else if (!form) {
result[v[0]] = value;
}
});
//如果設定的queryString:true並通過驗證,就返回form的提交字串.
if (result !== false && form && queryStr) result = CC.formQuery(form);
return result;
}

複製代碼 代碼如下:/**
* 應用對象替換模板內容
* templ({name:'Rock'},'<html><title>{name}</title></html>');
* st:0,1:未找到屬性是是否保留
*/
templ: function(obj, str, st) {
return str.replace(/\{([\w_$]+)\}/g, function(c, $1) {
var a = obj[$1];
if (a === undefined || a === null) {
if (st === undefined) return '';
switch (st) {
case 0:
return '';
case 1:
return $1;
default:
return c;
}
}
return a;
});
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.