簡體   English   中英

在jquery插件中鏈接非jquery方法

[英]Chain non-jquery methods in a jquery plugin

假設我寫了一個jquery插件,它的方法可以添加兩個值並將html設置為該值。 我可以采用一種方式進行鏈接,但不能采用另一種方式,並且我想了解原因以及如何確保可以采用兩種方式進行鏈接。

$.fn.foo = function() {
    this.result = 0;

    this.doMath= function(a, b) {
        this.result = a + b;
        this.html(this.val);
        return this;
    }

    return this;
}

var link = '<a href="#">Link</a>'
// works as expexted
var a = $(link).foo().doMath(1,2).appendTo('body')
// does not work, likely because appendTo returns jquery
var b = $(link).foo().appendTo('body').doMath(1,2)

https://jsfiddle.net/j7ut1f30/1/

經過2周的嘗試,我終於實現了自己的目標。

class $Util {

    static $wrapper(self) {
        if (!self.$wrapper)
            throw new ReferenceError('$Util.$wrapper: $wrapper not defined in context of first argument');
        $.each($Util.jqueryPrototype, function(i, e) {
            self[e] = function() {
                self.$wrapper[e](...arguments);
                return self;
            }
        });
    }
}

$Util.jqueryPrototype = Object.getOwnPropertyNames($.prototype);

class foo {
    constructor() {
        this.$wrapper = $('p')
        $Util.$wrapper(this);
        return this;
    }
    test() {
        console.log('j')
        return this;
    }
}
var s = new foo();
s.css('color', 'red').test().appendTo('body').test().css('color','green')

https://jsfiddle.net/24r6uxs1/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM