jQuery自定义插件功能验证选项 [英] Jquery custom plugin function validate options

查看:115
本文介绍了jQuery自定义插件功能验证选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我已经定义了一个JQuery函数,如下所示:

Let´s say I have defined a JQuery function as may be the following:

jQuery.fn.extend({
  objectParallax: function(speed) {
    var $window = $(window);
    return this.each(function() {
      var elem = $(this);
      var defaultTop = parseInt(elem.css('top'));
      $window.on('scroll', function() {
        var scrolled = $window.scrollTop();
        elem.css('top', (defaultTop - (scrolled * speed)) + 'px');
      });
    })
  }
});

我希望参数speed成为选项而不是参数(我的真实函数比这更复杂,并且它还有更多的参数,我也想成为选项).我怎样才能做到这一点?以及如何验证speed是-2到2之间的数字,如果不是,则会在控制台中引发错误?

I want the parameter speed to be an option instead of a parameter(my real function is a bit more complex than this, and it has a few more parameters which I also want to become options). How can I do this? And how can I validate that speed is a number between -2 and 2, and throw an error in console if it´s not?

推荐答案

现在,您要定义options对象,并且还传入一个对象而不是speed变量,并使用用户定义的选项扩展默认值

Now you want to define options object and also pass in an object instead of speed variable and extend the defaults with user defined options

基本知识如下:

jQuery.fn.extend({
  objectParallax: function(options) {

    // plugin defaults
    var defaults = {
      speed: '.5', // expect values between -2 & 2
      /* other properties and default values */   
    };

    // in case no user options object provided make sure we pass object to settings extend
    options = options ? options : {};

    // create settings by extending defaults with user defined opts
    var settings = $.extend({}, defaults, options);

    // ultra basic speed validation
    if (settings.speed < -2 || settings.speed > 2) {
      console.error('Speed not in limits');
      return;  // quit if not valid  
    }   

    var $window = $(window);
    return this.each(function() {
      var elem = $(this);
      var defaultTop = parseInt(elem.css('top'));
      $window.on('scroll', function() {
        var scrolled = $window.scrollTop();
        // use settings properties instead of `speed` argument
        elem.css('top', (defaultTop - (scrolled * settings.speed)) + 'px');
      });
    });
  });
});

现在,而不是在可以包含插件所需的任何或所有属性的options对象中传递字符串变量.如果您不包含属性/值,则插件将使用默认的

Now instead of passing string variable in pass in an options object that can contain any or all of the properties required by plugin. If you don't include a property/value then plugin will use the default

var opts = {speed: 1.5 };
$('#floating-parallax-1, #floating-parallax-2').objectParallax(opts);

jQuery学习中心/插件

关于jQuery插件模式以及样板网站和种子项目,网络上还有很多其他资源

There are also lots of other resources on web regarding jQuery plugin patterns as well as boilerplate sites and seed projects

这篇关于jQuery自定义插件功能验证选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆