我有問題讓選擇器被緩存,所以,基本上我沒有使用JQUERY框架。我創建了自己的模仿JQUERY模式的框架。Javascript緩存選擇器功能
這是我的代碼:
"use strict"
var $, i;
(function() {
$ = function(el) {
return new obj$(el);
};
var obj$ = function(el) {
var cl = document.getElementsByClassName(el),
loop = cl.length;
this.length = loop;
for (i = 0; i < loop; i++) {
this[i] = cl[i];
}
};
obj$.prototype = {
find : function(el) {
if (this.length == 1) {
this[0] = this[0].getElementsByClassName(el)[0]; // this is the problem, it's reset everything
return this;
}
},
css : function(obj, data) {
if (this.length == 1) {
this[0].style[obj] = data;
return this;
}
},
cache : function() {
if (this[0].hasOwnProperty("find")) {
return this[0]; // reset the selector from $() that has been hook by find function
}
else {
return this[0].find(); // do nothing if $() has not been hook by find function
}
}
};
})();
var parent = $("parent"), // i want this selector being cache
child = parent.find("child"); // but, when i hook this "find" function it's reset parent selector
child.css("color", "orange");
parent.css("color", "purple");
<div class="parent">parent
<div class="child">child</div>
</div>
的jsfiddle:https://jsfiddle.net/k6j70f1h/
輸出是:孩子與紫色,但是,爲什麼不父也成爲紫色的?我知道在我的find函數中,我使用這個[0] = this [0] .getElementsByClassName(el)[0];
所以,它重置$()對象選擇器。
如何防止此問題發生? 我只是看着hasOwnProperty方法。是否有可能創建另一個函數來檢查hasOwnProperty?
我希望$()對象保持它的選擇器甚至與查找函數鏈接?
任何建議傢伙?謝謝..
而不是創建自己的framwork一個行爲有點像jQuery的,爲什麼不使用jQuery? (如果你想要一個更小的變體,[zepto.js](http://zeptojs.com/))? – Tomalak
感謝Tomalak的評論,我會採取您的意見。但是,在不知道自己的成就如何不是我的風格的情況下做事。 –
我不知道這意味着什麼。如果它的意思是「我想自己寫所有的圖書館」,那麼我只能說這不是一個非常聰明的位置。 – Tomalak