【问题标题】:Javascript inheritence in jquery wayjquery方式的Javascript继承
【发布时间】:2015-06-11 08:28:16
【问题描述】:

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

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 那样以这种方式使用?

【问题讨论】:

标签: javascript oop object handle object-properties


【解决方案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

【讨论】:

  • 当我说 handle("p").next().next().innerHTML 返回 undefined
  • 已修复:现在您可以将 pdocument.querySelector('p') 作为参数传递。
  • 仍然 innerHTML 未定义它不能以这种方式工作@YauheniLeichanok
  • 你试过handle('p').next().elem.innerHTML吗?基本上我们在 elem 变量中引用了当前元素。
  • handle 在这种情况下应该返回一个元素节点,为什么我不能直接到达内部 html 属性@YauheniLeichanok
猜你喜欢
  • 2013-08-18
  • 1970-01-01
  • 1970-01-01
  • 2013-10-31
  • 2018-01-24
  • 1970-01-01
  • 2023-03-17
  • 2010-12-11
  • 1970-01-01
相关资源
最近更新 更多