簡體   English   中英

訪問$(document).ready()內部和外部的元素

[英]Accessing an element inside and outside of $( document ).ready()

我需要訪問$( document ).ready()范圍內部和外部的元素。

假設以下代碼:

var text__holder = $('#text__holder');

$(function() {
    text__holder.text('Inside DOM ready');
    /*
      SOME MORE ACTION WITH ELEMENT
    */
});

var writeSomeTxt = function () {
    text__holder.text('Outside DOM ready');
};

writeSomeTxt();

在這種情況下,我無法訪問函數內部的元素。 該JS也位於外部.js文件中,該文件包含在頁面的<head>部分中,我無法在其他地方替換它。

我目前的“解決方法”是:

var text__holder = $('#text__holder');

$(function() {
    text__holder.text('Inside DOM ready');
    /*
      SOME MORE ACTION WITH ELEMENT
    */
});

var writeSomeTxt = function () {
 $(function() {
    text__holder.text('Outside DOM ready');
 });
};

writeSomeTxt();

問題可能是您不能僅使用以下代碼行:

var text__holder = $('#text__holder');

直到已加載DOM。 如果這樣做,您只會得到一個空的jQuery對象,因為它將找不到任何匹配的DOM對象。

如果您知道在加載DOM之后才會調用writeSomeTxt() ,則可以這樣做:

var text__holder;

$(function() {
     text__holder = $('#text__holder');
     text__holder.text('Inside DOM ready');
    /*
      SOME MORE ACTION WITH ELEMENT
    */
});

var writeSomeTxt = function () {
    text__holder.text('Outside DOM ready');
};

// don't call this until after the DOM is loaded
// presumably based on some DOM event
writeSomeTxt();

但是,實際上,無論如何都試圖緩存單個DOM引用毫無意義,因此編寫代碼的更好方法是:

$(function() {
    $('#text__holder').text('Inside DOM ready');
    /*
      SOME MORE ACTION WITH ELEMENT
    */
});

var writeSomeTxt = function () {
    $('#text__holder').text('Outside DOM ready');
};

// don't call this until after the DOM is loaded
// presumably based on some DOM event
writeSomeTxt();

或者,如果所有這些代碼都應該在頁面初始化時運行,則只需將其全部放入.ready()處理函數中。

$(function() {
     var text__holder = $('#text__holder');
     text__holder.text('Inside DOM ready');
    /*
      SOME MORE ACTION WITH ELEMENT
    */

    var writeSomeTxt = function () {
        text__holder.text('end of DOM ready');
    };

    writeSomeTxt();

});

您可以在document.ready外部聲明函數和變量,並在定義變量之后在內部定義變量和調用函數:

var text__holder;//declare undefined varible

$(function() {

    text__holder = $('#text__holder');// can now define varible
    text__holder.text('Inside DOM ready');        
    // call function now that variable is defined
    writeSomeTxt();
});

var writeSomeTxt = function () {
    text__holder.text('Outside DOM ready'); 
};

暫無
暫無

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

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