如何在没有Jquery的情况下链接Javascript?

时间:2014-12-30 07:16:11

标签: javascript

当我搜索JS链接的答案时,我得到类似j-query的内容。

$("#wrapper").fadeOut().html("Welcome, Sir").fadeIn();

我想知道是否有任何与j-query无关的链接方法。 请。

4 个答案:

答案 0 :(得分:4)

您可以通过返回方法中的上下文来组织链接,例如

var chaining = {
    do: function(){
        // code here...
        return this;
    },
    stuff: function(){
        // and here...
        return this;
    }
}
chaining.do().stuff()

答案 1 :(得分:2)

链接是可能的,因为jQuery中的每个方法都返回一个jQuery对象。初始调用($())创建一个jQuery对象。其余的是返回jQuery对象的jQuery方法。您可以返回相同的实例或创建一个新实例。在jQuery的例子中,他们创建了新对象。

这是一个简单的对象,它的方法返回自己。

function CustomObject(){
  if(!(this instanceof CustomObject)) return new CustomObject();
}

CustomObject.prototype.aMethod = function(){
  // do something
  return this;
}

CustomObject.prototype.anotherMethod = function(){
  // do something else
  return this;
}

// Use like
var a = CustomObject()
var b = a.aMethod().anotherMethod().anotherMethod();
a === b

答案 2 :(得分:0)

是的。 t是简单的责任链设计模式。 链接到示例: http://www.dofactory.com/javascript/chain-of-responsibility-design-pattern

简而言之,您的方法必须返回此(引用当前对象)

答案 3 :(得分:0)

链接不是魔术,如果返回的元素是初始对象集的子集,则只应用链接。因此你不能使用$(“#wrapper”)。fadeOut()。html()。fadeIn();

因为当您使用此.html()版本m时,返回的元素不是jquery对象,因此链断开。对于javascript也一样。

相关问题