87,994
社区成员
发帖
与我相关
我的任务
分享function batch(fn){
return function(target, ...args){
if(target.length >= 0){
return Array.from(target).map(item => fn.apply(this, [item, ...args]));
}else{
return fn.apply(this, [target, ...args]);
}
}
}
function queriable(fn){
return function(selector, ...args){
if(typeof selector === 'string'){
selector = document.querySelectorAll(selector);
}
return fn.apply(this, [selector, ...args]);
}
}
function pack(map){
return function(el, ...obj){
// 修改1:当输入为一个键值对的时候可以用传入2个字符串替代
// 第一个为键,第二个为值
if(obj.length==1){
for(let key in obj[0]){
map[key].call(this, el, obj[0][key]);
}
} else {
map[obj[0]].call(this, el, obj[1])
}
}
}
function methodize(fn, prop){
return function(...args){
fn.apply(null, [prop ? this[prop] : this, ...args]);
return this;
}
}
function setColor(el, color){
el.style.color = color;
}
function setFontSize(el, fontSize){
el.style.fontSize = fontSize;
}
function setHTML(el, text){
el.innerHTML = text;
}
let css = pack({color: setColor, fontSize: setFontSize});
css = queriable(batch(css));
let html = queriable(batch(setHTML));
function E(selector){
this._selector = selector;
}
E.prototype.css = methodize(css, '_selector');
E.prototype.html = methodize(html, '_selector');
function $(selector){
return new E(selector);
}
$('ul > li:nth-child(2n + 1)').css({color: 'red', fontSize: '17px'});
$('ul > li:nth-child(2n)').css({color: 'green', fontSize: '22px'});
上面贴错了
<script>
function queriable(fn){
return function(els, ...args){
if(typeof els === 'string'){
els = document.querySelectorAll(els);
}
return fn.apply(this, [els, ...args]);
}
}
function batch(fn){
return function(items, ...args){
if(items.length && items.length >= 0){
return Array.from(items).map(item => fn.apply(this, [item, ...args]));
}else{
return fn.apply(this, [items, ...args]);
}
}
}
function fold(fn){
return function(...args){
if(args.length > 0 && args.length < fn.length){
let map = args[args.length - 1];
if(map != null && typeof map === 'object'){
args.pop();
let ret = [];
for(var key in map){
ret.push(fn.apply(this, args.concat([key, map[key]])));
}
return ret;
}
}
return fn.apply(this, args);
}
}
function compose(...functors){
return functors.reduceRight((a, b) => b(a));
}
function setStyle(el, key, value){
el.style[key] = value;
}
setStyle = compose(queriable, batch, fold, setStyle);
function $(selector){
return new iQuery(selector)
}
function iQuery(selector){
this.selector = selector
}
setStyle('#list li:nth-child(2n+1)', 'color', 'red');
setStyle('#list li:nth-child(2n)', {
'color': 'green',
'fontSize': '20px'
});