我意识到使用jQuery为我当前的项目有点过度杀戮,因为我只使用了~10种方法(最多)所以我决定使用API风格的jQuery创建一个更小的库。
库的功能(称为Lib)返回3个属性:
结果(包含查询结果)
selector(包含用于获取结果的选择器)
长度(结果的长度)
图书馆的功能如下所示:
function Lib(selector, context) {
context = context || window.document;
if(window === this) {
return new Lib(selector, context);
}
this.results = map(context.querySelectorAll(selector));
this.selector = selector;
this.length = results.length;
return this;
}
地图功能:
function map(collection) {
var results = [];
for(var i = 0; i < collection.length; i++) {
results.push(collection[i]);
}
return results;
}
每次从Lib.prototype中的方法访问“this”对象时,我都必须使用this.results来修改this.selector元素以获取选择器和this.length来获取长度。
是否可能使用元素和属性污染“this”对象
E.G:使用“this”对象访问元素,
“this.selector”属性访问选择器和
“this.length”访问元素的长度?
另外我该如何实现呢?
对于那些想知道这些是(完整的)方法列表的人:
Lib("div").html("<div id=\"div-one\">Some Awesome HTML</div>")
Lib("div").text("Some Awesome Text")
Lib("div").attr("placeholder", "Search")
Lib("div").attr("placeholder")
Lib("div").css("background-color", "#fff")
Lib("div").css("background-color")
Lib("div").on("type", function(){/* do something when div has been clicked */})
Lib("div").off("type", function(){/* do something when div has been clicked */})
Lib("div").each(function(index, value){/* loop through each div and do something with them */})
Lib("input").blur(function(){/* do something when the focus has left input */})
Lib("input").focus(function(){/* do something when input has been focused on */})
注意:请不要费心支持IE&lt; 9(IE 6-9需要死)
答案 0 :(得分:0)
在原型中将results
,length
,selector
等属性分配和访问为this.prop
是一种很好的做法,否则您将无法获取您的方法在上执行的范围的实际值,因此基本上您只能使用this
访问它们。
有用的链接:
答案 1 :(得分:0)
查找
var AP = []; //utility
function Lib(selector, context) {
var me = Object.create(Lib.prototype, {
selector: { configurable: true, value: selector },
length: {writable: true, value: 0}
});
AP.push.apply(me, (context || document).querySelectorAll(selector));
return me;
}
Lib.prototype.each = function(fn){
for(var i=0, j=this.length; i<j; ++i)
//if(false === fn(this[i], i, this)) break;
fn(this[i], i, this);
return this;
}
答案 2 :(得分:0)
你需要使用它的索引将每个元素推送到这个:
function Lib(selector, context) {
context = context || window.document;
if(window === this) {
return new Lib(selector, context);
}
results = context.querySelectorAll(selector);
this.length = results.length;
for(var i = 0; i < results.length; i++) {
this[i] = results[i];
}
this.selector = selector;
this.context = context;
return this;
}
function map(collection) {
var results = [];
for(var i = 0; i < collection.length; i++) {
results.push(collection[i]);
}
return results;
}
Lib.fn = Lib.prototype = {};
window.Lib = window.$ = Lib;
您现在可以:
Lib("div") // get all divs in document
Lib("div", document) // also get all divs in document
Lib.fn.getSelector = function() {
// you can now access individual elements using their index
alert(this[0].selector);
};