Best practices for declaring functions inside jquery ready function

前端 未结 3 1498
迷失自我
迷失自我 2020-12-24 06:08

I haven\'t found a good reference for declaring my own functions inside the

jquery.ready(function(){});

I want to declare them so they

相关标签:
3条回答
  • 2020-12-24 06:53

    I have a StartUp function, and I use it as printed bellow:

    function StartUp(runnable)
    {
        $(document).ready(runnable.run);
    }
    
    var ExternalLinks =
    {
        run: function()
        {
            $('a[rel="external"]').bind('click', ExternalLinks.click);
        },
        click: function(event)
        {
            open(this.href);
            return false;
        }
    }
    StartUp(ExternalLinks);
    
    var ConfirmLinks =
    {
        run: function()
        {
            $('a.confirm').bind('click', ConfirmLinks.click);
        },
        click: function(event)
        {
            if (!confirm(this.title)) {
                return false;
            }
        }
    }
    StartUp(ConfirmLinks);
    

    My web sites are modular, so every module has N actions and every action can have a .js file, so I just write function and call it with StartUp(...functionName...)

    0 讨论(0)
  • 2020-12-24 06:58

    I believe that you would be okay just declaring the function inside the ready() closure, but here you can be a bit more explicit about the local scoping:

    jQuery.ready(function() {
    
         var myFunc = function() {
    
               // do some stuff here
    
         };
    
         myFunc();
    
    
    });
    
    0 讨论(0)
  • 2020-12-24 07:06

    It might sound simple but you just ... declare the function. Javascript allows functions to have inner functions.

    $(document).ready( function() {
       alert("hello! document is ready!");
    
       function multiply(a, b) {
           return a * b;
       }
    
       alert("3 times 5 is " + multiply(3, 5));
    });
    
    0 讨论(0)
提交回复
热议问题