当前位置: 代码迷 >> JavaScript >> Javascript:object [method]()无效或如何为普通的Javascript代码构建jQuery插件
  详细解决方案

Javascript:object [method]()无效或如何为普通的Javascript代码构建jQuery插件

热度:96   发布时间:2023-06-05 11:48:58.0

我需要帮助为我的一个vanilla JS脚本制作一个jQuery插件, 是当前的jQuery插件,但下一个版本使用更多方法,我需要以某种方式解决它们。

目前我正在研究这个问题

(function($) {
    var t;  
    $.fn.KUTE = function( method, start, end, ops ) { // method can be Animate(), fromTo(), to(), stop(), start(), chain(), pause(), stop(), etc
        return this.each(function(){        
            if ( method === 'to' ) {                
                t = new KUTE[method]( this, null, end, ops );
            } else if ( method === 'fromTo' || method === 'Animate' ) {
                t = new KUTE[method]( this, start, end, ops );
            } 
            if ( t !== undefined && typeof t[method] === 'function' ) {
                console.log(t) // this shows proper object
                t[method]() // this doesn't work
            }   
        });
    };  
})(jQuery);     

为什么t[method]()不起作用,我怎样才能使它工作?

更新:我在这里添加一些关于如何解决此代码的示例代码。 基本上我构建了一个补间对象

var tween = $(div).KUTE('to', { left: tl }, { easing: easing, duration: 1000 } );

然后我需要start()它, stop()它和其他方法。

$(tween).KUTE('start'); // this should basically be it.

现在,我一直在阅读一些Javascript的东西,如call()apply() ,我有点认为这可能是必需的,但是即使如此t[method].call(t) // where t is "this" ,不起作用。 我希望我说得对,表明我的问题,如果有任何错误,请纠正我。

非常感谢。

我想我找到了原因,我上面的上一条评论解释了它,我做了一个不同的jQuery函数。

(function($) {
    $.fn.KUTE = function( method, start, end, ops ) { // method can be Animate(), fromTo(), to(), stop(), start(), chain(), pause() 
        var tws = [], i, l = this.length;

        for (i=0;i<l;i++){
            var mt = this[i][method];
            if ( typeof mt === 'function' ) {
                mt.apply(this[i]);
            }    
            if ( method === 'to' ) {
                tws.push( new KUTE[method]( this[i], start, end ) ); // here start is end and end is ops 
            } else if ( method === 'fromTo' || method === 'Animate' ) {
                tws.push( new KUTE[method]( this[i], start, end, ops ) ); 
            }           
        }
        return tws;
    };
})(jQuery); 

接下来要做的是,如果this.length > 1做一个不错的小FOR()而不是超级糟糕和丑陋的jQuery.each()

问题已解决,请参阅我的以获取示例。

更新:我还添加了FOR ,它按预期工作。 我更新了上面的答案。

  相关解决方案