문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top