因为想做 iPhone 的 Web 应用,这些天一直在找一个轻量的 javascript 库。
今天终于找到一个可用的:
http://www.freelancephp.net/light-4kb-mini-jquery/这个库仅实现了 jQuery 的一部分功能,且限于 DOM 操作,不过目前对我来说已经足够。
这个库的代码非常简单易懂,因此很容易扩展。为了实现更多的 jQuery 基本功能,我追加了几个函数:
hasClass, hide, show, html, text, val, find我追加的代码如下:
// determine className
hasClass: function ( className ) {
for ( var i = 0; i < this.els.length; i++ ) {
if(this.els[i].className.match(new RegExp('\\b' + className + '\\b')))
return true;
}
return false;
},
// hide elements
hide: function () {
this.each(function( el ) {
el.style.display = 'none';
});
return this;
},
// show elements
show: function () {
this.each(function( el ) {
el.style.display = 'block';
});
return this;
},
// set inner html
html: function (value) {
if(value == undefined) {
return this.els[0] ? this.els[0].innerHTML : '';
}
this.each(function( el ) {
el.innerHTML = value;
});
return this;
},
// set inner text
text: function (value) {
var name = (document.body.textContent != undefined) ? 'textContent' : 'innerText';
if(value == undefined) {
return this.els[0] ? this.els[0][name] : '';
}
this.each(function( el ) {
el[name] = value;
});
return this;
},
// set value
val: function (value) {
if(value == undefined) {
return this.els[0] ? this.els[0].value : '';
}
this.each(function( el ) {
el.value = value;
});
return this;
},
// find children
find: function (selector) {
return new this.init( selector, this.get(0) );
},
修改后的文件:
light.jslight.min.js这个库的选择器部分,仅仅是 getEmelentById, getElementsByName 的简单扩展。如果需要用到类似 $("td:eq(2)") 甚至更复杂的选择器,就得另想办法了。幸运的是,这个库提供了接口,你可以采用以下的选择器代码:
Sizzle,
Sly,
NWMatcher,
Peppy,
Yass方法很简单:
Light.selector = Sly; // use Sly engine
Light.selector = Sizzle; // use Sizzle engine
Light.selector = NW.Dom.select; // use NWMatcher engine
Light.selector = peppy.query; // use Peppy engine
Light.selector = _; // use YASS engine