Javascript create next() function OOP way
Javascript create next() function OOP way
我在使用 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");
为什么这段代码不起作用? 控制台上没有错误。
我的代码有什么问题?
提前感谢...
(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");
你有很多工作要做,让你的按照你想要的方式工作。首先,你的选择器过程非常弱,第二,你对长度和对象的理解也非常薄弱。
相关文章:
- 直接在函数声明上使用function.prototype.bind
- jQuery:.click(function(){(element),collapse('show',f
- 如果连接类型为none,则Javascript Function Only警报
- onLoad function phonegap android
- reducers在redux中得到Function not Object,what'it’他错了
- WIll window.addEventListener(“加载”,function(),false);等待浏览器自动填
- Google Data API上的OOP Javascript回调方法
- $(document).ready和jQuery(function($)不工作;jQuery已定义,但脚本尚未定义;t进
- Javascript oop instances
- Javascript onunload function
- 在init function()中调用getElementById(“..”),而不是想用它做点什么的函数
- spyOn:应为间谍,但得到了Function
- jQuery each()没有'使用OOP方法是行不通的
- JavaScript中的OOP太令人困惑了,ES6很棒,但没有得到很好的支持,该怎么办
- (typeof variable === “function”) 和 jQuery.isFunction() 有什么区别
- this内部的值返回this.each(function(){})
- 如何在JavaScript中创建类似于something.function()的函数
- 如何通过 Function.prototype.apply() 更改调用函数的参数
- 控制台中的“function floor(){[本机代码]}”是什么
- Javascript create next() function OOP way