gpt4 book ai didi

Javascript 类返回数组,像 jQuery 一样创建库

转载 作者:行者123 更新时间:2023-11-30 14:10:46 25 4
gpt4 key购买 nike

我正在创建像 jQuery 这样的 javascript 库,我已经成功地添加了原型(prototype) html() 但是如果我用 $(selector) 调用它它会返回像 {'el' : [array]} 如果函数更改为 return this.el; 它返回数组但我不能调用 .html().

如何在不破坏原型(prototype)的情况下返回 [array]

window.$ = function(selector) {
if (!(this instanceof $)) {
return new $(selector);
}
this.el = [];
this.html = function(str) {
this.el.forEach(function(el) {
el.innerHTML = str;
});
};

(function(self) {
for (var eList = document.querySelectorAll(selector), i = eList.length - 1; i > -1; i--) {
self.el[i] = eList[i];
}
})(this);

return this;
};

$('#test').html('BBBBB')
console.log($('#test')[0])
<div id="test">AAAAAAA</div>

最佳答案

 window.$ = function(selector) {
var x = [];
x = document.querySelectorAll(selector);
console.log(x);
return x;
};
NodeList.prototype.html = function(str) {
console.log(this);
this.forEach(function(el){
el.innerHTML = str;
});
}


console.log($('#test').html('BBBBB'))
<div id="test"></div>

我在 NodeList 数组中扩展了 html 方法。告诉我它是否适合你。

关于Javascript 类返回数组,像 jQuery 一样创建库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54505721/

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