Domanda

OK, yesterday I asked about this but there was a stupid bug in my code so I ended up getting the answer to the wrong question.

I want to use JQuery inside a javascript constructor function, which sits inside a namespace:

var NS=NS||{};

NS.constructor=function()
{
    this.problem="doing my head in"
    this.solution="looking very messy"

    function useJQuery()
    {
        $(document).ready
        (
             function()
            {
                 $('body').html("I've written out the whole 'document ready function thing");
            }
         )
    }

    function usePlainJS()
    {
            return "Now I'm using plain JS";
    }

    function useJQueryAgain()
    {
        $(document).ready
        (
            function()
            {
                $('body').html("Now I've written out the 'document ready' thing AGAIN!");
            }
         )
    }

}

Is there a better way of doing this, without writing out the whole 'document ready' thing every time I want to use JQuery?

È stato utile?

Soluzione

Approach one. You can avoid repetitive $(document).ready blocks if you wrap function invocations themselves into $(functionName). For example:

var NS = NS || {};

NS.constructor = function() {   
    this.problem = "doing my head in"
    this.solution = "looking very messy"

    // Here is an example of usage this function
    $(useJQuery);

    function useJQuery() {
        $('body').html("I've written out the whole 'document ready function thing");
    }

    function usePlainJS() {
        return "Now I'm using plain JS";
    }

    function useJQueryAgain() {
        $('body').html("Now I've written out the 'document ready' thing AGAIN!");
    }
};

Approach two. Put all your code before closing </body> tag, after the rest of the DOM contents. This way you don't have to worry about document ready, because by the moment script is executed HTML structure is already available.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top