2010-09-13 88 views
3

爲什麼不能正常工作?也許有人可以啓發我:P原型和document.getElementById()

var balloon = function(){ 

}; 
balloon.prototype.iHeight = document.getElementById("wrapper").clientHeight; 

window.onload = function(){ 
    var oBalloon = new balloon(); 
} 

我只是想了解更好一點的原型。

+0

後你是什麼只被使用的文件裏面試圖做什麼? – jrharshath 2010-09-13 20:30:29

+1

@他在這裏說過......「我只是想更好地理解原型。」 – RobertPitt 2010-09-13 21:04:58

+0

嗯,點了。我承認。 – jrharshath 2010-09-13 21:56:19

回答

1

對象已經被初始化之後使你的代碼更改爲 原型只允許以下:

好像經過一番研究,我錯了,什麼問題看起來是你之前使用document.*事實窗口已加載,document.*僅在<body>已加載到DOM中時纔可用。

所以GetElementById()將只有一次你去選擇實際的單元工作是DOM

var ById = function(i){return document.getElementById(i);} 
var balloon = function(){} 

window.onload = function(){ 
    //All elements have loaded now 
    var oBalloon = new balloon(); 
    //The below code should work fine 
    balloon.prototype.iHeight = ById("wrapper").clientHeight; 
} 

從上面可以看到窗口加載

+0

不完全正確。 'balloon'已經被函數聲明初始化了。 '原型'在他有的地方很好。 – palswim 2010-09-13 20:54:07

+0

是的我的錯誤是原型可以添加到一個對象,無論其狀態,但只能訪問一次對象的構造。 – RobertPitt 2010-09-13 20:58:20

2

您的代碼可能在DOM加載之前運行,當沒有wrapper元素時。

0

也許你也想嘗試:

var balloon = function(){ 
}; 
balloon.prototype.iHeight = function(){ return document.getElementById("wrapper").clientHeight; } 

然後你就可以再打吧,DOM加載後。

你需要一個函數,否則JavaScript會嘗試在定義時計算該值。

window.onload = function(){ 
    var oBalloon = new balloon(); 
    var height = oBalloon.iHeight(); // iHeight would be undefined if you tried to calculate it earlier 
} 

你可以只散夥的原型方法,並在onload處理程序設置屬性:

window.onload = function(){ 
    var oBalloon = new balloon(); 
    oBalloon.iHeight = document.getElementById("wrapper").clientHeight; 
} 

然後,你就只能設置一次,也保證了DOM將已加載和財產將在那時有效。

你有什麼等價於:

var balloon = function(){}; 
var tmp = document.getElementById("wrapper").clientHeight; // at this point, this is not definted: tmp = undefined 
balloon.prototype.iHeight = tmp; // undefined 
window.onload = function(){ 
    var oBalloon = new balloon(); 
} 
+0

這有效,但它爲什麼需要包裹在一個函數中? – Baijs 2010-09-13 20:42:04

+0

這是因爲您的代碼可能在加載DOM之前運行。你的代碼工作正常,但你需要它在DOM加載後運行。 – cleek 2010-09-13 20:46:10

0

,您張貼優秀作品的代碼。你確定你有一個元素的id是包裝?