JQuery 插件函数调用

JQuery plugin function calling

我想从我的页面调用 jquery 插件函数,但我失败了:(。我的代码是:

var pstps=$('#psteps_simple_horiz_layout').psteps({
        steps_width_percentage: true,
        alter_width_at_viewport: '1300',
        steps_height_equalize: true
    });
    step_num=2;
    pstps.go_to_step(step_num);

该插件是 Pine Steps 向导。它的代码是:

function($) {
$.fn.psteps = function(options) {
    // Build main options before element iteration.
    var opts = $.extend({}, $.fn.psteps.defaults, options);

    // Iterate and transform each matched element.
    var all_elements = this;
    all_elements.each(function(){
        var psteps = $(this);
        psteps.psteps_version = "0.0.1alpha";
        .......................................................
        psteps.go_to_step = function(step_num){
            var last_active_title = psteps.find('.step-title.last-active'),
            .......................................................
        };
        .......................................................
        this.pines_steps = psteps;
    });

    return all_elements;
};

当我 运行 我的代码出现错误时:

Uncaught TypeError: undefined is not a function

它在下一行失败,因为 go_to_steps 不是 jQuery 扩展(并且 psteps() 的 return 值是原始 jQuery对象:

pstps.go_to_step(step_num);

您需要实际插件的实例。查看插件代码,它将实例连接为名为 pines_steps 的 DOM 元素上的 属性,因此您需要将 属性 作为您的 class实例:

var pstps=$('#psteps_simple_horiz_layout').psteps({
    steps_width_percentage: true,
    alter_width_at_viewport: '1300',
    steps_height_equalize: true
})[0].pines_steps;

那你可以打电话给

pstps.go_to_step(step_num);

常用模式:

编写插件的通常方式是在第一个参数中也接受函数名称作为字符串,这样它们就可以像这样调用方法:

$('#psteps_simple_horiz_layout').psteps("go_to_step", step_num);

但是这个插件缺少执行此操作的代码