簡體   English   中英

頁面正確加載后檢查div屬性

[英]Checking div properties once page has loaded correctly

現在我想檢查頁面加載時的元素大小。 我一直在使用$(document).ready(); ,但發現這些屬性通常為null。 如果我使用$(window).load();也是如此$(window).load();

為了解決這個問題,我一直在使用一些技巧,如果未設置元素,則會遞歸地調用該函數。

問題:在專業性方面是否有更好的方法?

var makeMusic = {

    init: function() {
        if ($('#bloc-1').height() == null) {
            setTimeout(function() {
                makeMusic.init() ########## THIS IS THE HACK ##########
            }, 10)
        } else {
            makeMusic.height = $('#bloc-1').height();
            makeMusic.width = $('#bloc-1').width();
        }       
        makeMusic.watchExperience();
    },

    watchExperience: function() {
      //Some stuff
    }
}


var Main = {
    run: function() {
        makeMusic.init();
    }
}

$(document).ready(Main.run());

您根本不需要黑客。 這里的問題是在Main.run document.ready()之前調用Main.run函數。 你應該:

$(document).ready(Main.run);

代替

$(document).ready(Main.run());

當您在函數名稱中添加() ,interpeter會在到達該行時立即調用它。

傳遞回調時,應僅傳遞對該函數的引用。

就專業性而言,我認為最好將代碼放在這樣的名稱空間中:

 var app = window.app || {};
 app.set = {};
 app.set.makeMusic = (function(){

     // private members
     this.height = "";
     this.width = "";

     var init = function() {
         height = $('#bloc-1').height();
         width = $('#bloc-1').width();
         alert(height + " " + width);
     };

     //public interface
     return {
         init: init
     };

 })(); // self invoked

 $(function(){
     app.set.makeMusic.init();
 });

小提琴

暫無
暫無

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

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