如何使用括号和参数创建自定义jquery函数 [英] How to create a custom jquery function with brackets and parameters

查看:97
本文介绍了如何使用括号和参数创建自定义jquery函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我的问题需要更多澄清,所以让我解释一下:



当我访问$ .fn.extend的jquery api文档时,我是亲自吹嘘创建这样的自定义jquery函数是多么容易:

  $('input [type =复选框]')。校验(); 

链接到这里: http://api.jquery.com/jquery.fn.extend/



但是如果你想要像这样添加功能(双关语):

  check({timer:1000,redo:4000,displayAt:' someID'}); 

//填充参数

你准备怎么做?



另外,你如何创建一个像 check({...}); 这样不依赖的函数在任何特定的jquery选择器上,但可以像这样的常规函数​​调用:

  displayRandomNumber({min:0, max:100,displayAt:'someID'}); 

//所以前面没有jquery选择器。

感谢您的帮助!

如果你想使用:

  check({timer:1000,redo:4000, displayAt:'someID'}); 

使用jquery.fn.extend你的函数将被声明如下:

  check:function(options){
//获取计时器值
var timerValue = options.timer;
//获取重做值
var redoValue = options.redo;
...
}

独立,它看起来像这样: / p>

 函数检查(选项){
//获取计时器值
var timerValue = options.timer;
//获取重做值
var redoValue = options.redo;
...
}


I know that my question needs a little more clarification, so let me explain:

When I visited the jquery api documentation for $.fn.extend, I was personally blown away by how easy it was to create a custom jquery function like this:

$('input[type="checkbox"]').check();

Link here: http://api.jquery.com/jquery.fn.extend/

But if you wanted to add functionality to the function like this (pun intended):

check({ timer: 1000, redo: 4000, displayAt: 'someID' });

// filler parameters

How would you do that, exactly?

Also, how would you create a function like check({ ... }); that does not rely on any specific jquery selectors, but instead could just be called like a regular function like this:

displayRandomNumber({ min: 0, max: 100, displayAt: 'someID'}); 

// so no jquery selector in front.

Thanks for your help!

解决方案

If you want to use:

check({ timer: 1000, redo: 4000, displayAt: 'someID' });

with jquery.fn.extend your function would be declared like so:

check: function(options) {
    // Get the timer value
    var timerValue = options.timer;
    // Get the redo value
    var redoValue = options.redo;
    ...
}

Standalone, it would look like this:

function check(options) {
    // Get the timer value
    var timerValue = options.timer;
    // Get the redo value
    var redoValue = options.redo;
    ...
}

这篇关于如何使用括号和参数创建自定义jquery函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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