gpt4 book ai didi

Javascript 创建 next() 函数 OOP 方式

转载 作者:行者123 更新时间:2023-11-29 16:04:16 27 4
gpt4 key购买 nike

我在使用 OOP 方式创建 next() 函数时遇到了问题。

这是 fiddle :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");

要使您的系统按您希望的方式工作,您还有很多工作要做。一是你的选择过程很薄弱,二是你对长度和对象的理解也很薄弱。

关于Javascript 创建 next() 函数 OOP 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35568443/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com