如果我在对象下设置一个函数,我只能使用它一次
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的方式使用?
答案 0 :(得分:1)
说到你的功能,你可以像这样修改它以使它工作:
function handle(selector)
{
if (typeof selector === 'string') {
selector = document.querySelector(selector);
}
return{
elem:selector,
next:function(){
return handle(selector.nextElementSibling);
}
}
}
请参阅jsfiddle。
UPD:修改代码以支持元素和字符串选择器作为参数。
UPD 2:推出另一种变体。在这种情况下,我们扩展本机html元素对象并添加新的 next 方法:
function handle(selector)
{
if (typeof selector === 'string') {
selector = document.querySelector(selector);
}
selector.next = function() {
return handle(selector.nextElementSibling);
};
return selector;
}
小提琴是here。