簡體   English   中英

如何在JS名稱空間內的構造函數內使用JQuery?

[英]How do I use JQuery inside a constructor function inside a JS namespace?

好的,昨天我問了這個問題,但是我的代碼中有一個愚蠢的錯誤,所以我最終得到了錯誤問題的答案。

我想在位於名稱空間內的javascript構造函數內使用JQuery:

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!");
            }
         )
    }

}

有沒有一種更好的方法,而不必每次我想使用JQuery都寫出整個“文檔就緒”的東西?

方法一。 如果將函數調用自身包裝到$(functionName)則可以避免重復的$(document).ready塊。 例如:

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!");
    }
};

方法二。 將所有代碼放在</body>標記之前,其余DOM內容之后。 這樣,您不必擔心文檔是否准備就緒,因為在執行腳本時,HTML結構已經可用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM