gpt4 book ai didi

jquery方式的Javascript继承

转载 作者:行者123 更新时间:2023-11-30 00:31:02 24 4
gpt4 key购买 nike

如果我在一个对象下设置一个函数,我只能使用它一次

function handle(selector)
{
return{
elem:selector,
next:function(){
return (this.nextSibling.nodeType==1) ? this.nextSibling : this.nextSibling.nextSibling;
}
}
}

在这里我可以说 handle.next() 这会起作用,但是如果我想说 handle.next().next().next() 我的问题是如何像 jquery 一样使用这种方式的?

最佳答案

谈到您的功能,您可以像这样修改它以使其工作:

function handle(selector)
{
if (typeof selector === 'string') {
selector = document.querySelector(selector);
}
return{
elem:selector,
next:function(){
return handle(selector.nextElementSibling);
}
}
}

参见 jsfiddle .

更新:修改代码以支持元素和字符串选择器作为参数。

UPD 2:推出了一个替代变体。在这种情况下,我们扩展 native html 元素对象并添加新的 next 方法:

function handle(selector)
{
if (typeof selector === 'string') {
selector = document.querySelector(selector);
}
selector.next = function() {
return handle(selector.nextElementSibling);
};
return selector;
}

fiddle 是 here .

关于jquery方式的Javascript继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29479782/

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