简体   繁体   中英

Advanced javascript calling plugin function within function

 (function($) {
     $.fn.extend({
     clock: function(options) {
     var options = $.extend(defaults, options);
        .......
        .......
        return this.each(function() {
         var prev = function() {
                console.log("hello world!");
            alert('getweather');
            };
            $('#left').click(function() {alert(342);});

      });
})(jQuery); 

how to call the plugin functions prev and $('#left') from below code

 $.fn.clock().prev(); //doesn't work

 $.fn.clock('#left');   //doesn't work

thanks in advance

You cannot, based on the code provided. It is impossible. The function is assigned to the local variable prev , which is not being exposed outside the local scope in any way.

If you want to make it accessible, you need to store the function somewhere such that it won't go out of scope, and then provide some interface, typically via something like $('my-element').clock('prev') . jQuery Plugin Authoring explains best practices for exactly this, specifically under Plugin Methods .

Those are anonymous functions. Even if they were within your scope, you wouldn't be able to call them.

A workaround would be to trigger a click event on #left :

$('#left').trigger('click');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM