How to create a custom jquery function with bracke

2019-03-05 15:51发布

问题:

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!

回答1:

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;
    ...
}