JQuery插件函数调用

时间:2015-02-18 09:41:13

标签: javascript jquery jquery-plugins

我想从我的页面调用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

1 个答案:

答案 0 :(得分:0)

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

pstps.go_to_step(step_num);

您需要实际插件的实例。查看插件代码,它将实例作为名为pines_steps的DOM元素的属性进行连接,因此您需要将该属性作为类实例获取:

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);

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