我有一个使用OOP方式创建next()函数的问题。
这是小提琴:https://jsfiddle.net/s5e1530c/
"use strict";
var i, j, arr, loop, $;
(function() {
$ = function(el, context) {
context = context || document;
return new obj$(el, context);
};
var obj$ = function(el, context) {
if (context == null) {
var cl = context.getElementsByClassName(el),
loop = cl.length;
this.length = loop;
for (i = 0; i < loop; i++) {
this[i] = cl[i];
}
}
else {
var cl = context,
loop = cl.length;
this.length = loop;
for (i = 0; i < loop; i++) {
this[i] = cl[i];
}
}
return this;
};
obj$.prototype = {
next : function() {
if (this.length == 1) {
return $(this[0], this[0].nextElementSibling);
}
return $();
},
css : function(obj, data) {
if (this.length == 1) {
this[0].style[obj] = data;
}
return this;
}
};
})();
<div class="child">child</div>
<div class="next">Next</div>
var child = $("child"),
nextchild = child.next();
nextchild.css("color", "red");
为什么这段代码不起作用?控制台上没有错误。
我的代码出了什么问题?
提前感谢......
答案 0 :(得分:0)
(function() {
"use strict";
var i, j, arr, loop, $, Obj$;
$ = function(el, context) {
context = context || document;
return new Obj$(el, context);
};
Obj$ = function(el, context) {
if(typeof el == "object") {
//take care of objects here
}
/*
why would context be null? It's either context or document
if (context == null) {
var cl = context.getElementsByClassName(el),
loop = cl.length;
this.length = loop;
for (i = 0; i < loop; i++) {
this[i] = cl[i];
}
}
else {
*/
var cl = context.getElementsByClassName(el),
loop = cl.length;
this.length = loop;
for (i = 0; i < loop; i++) {
this[i] = cl[i];
}
//}
return this;
};
Obj$.prototype = {
next : function() {
//why do equals 1? Do greater than or equal to 1
if (this.length >= 1) {
return $(this[0].nextElementSibling);
}
//return undefiend not an empty object
return undefined;
},
css : function(obj, data) {
if (this.length >= 1) {
this[0].style[obj] = data;
}
return this;
}
};
window.$ = $;
})();
var child = $("child"),
nextchild = child.next();
nextchild.css("color", "red");
您需要做很多工作才能让您按照自己的方式工作。对于你的选择过程非常弱,你对长度和物体的理解也非常微弱。