简体   繁体   English

prototype和document.getElementById()

[英]prototype and document.getElementById()

Why doesn't this work? 为什么这不起作用? Maybe someone could enlighten me :P 也许有人可以启发我:P

var balloon = function(){

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

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

Im just trying to understand prototype a little better. 我只是想更好地了解原型。

在没有wrapper元素的情况下,您的代码可能在DOM加载之前运行。

prototypes are only allowed after the object has been initialized so change your code to the following: 只有在初始化对象后才允许原型,因此请将代码更改为以下内容:

Seems after some research I was wrong, what the problem looks like is the fact that your using document.* before the window has loaded, document.* is only available once the <body> has been loaded into the DOM. 似乎在经过一些研究之后我错了,问题是你在使用document.*之前加载了窗口document.*只有在<body>加载到DOM之后才能使用document.*

so GetElementById() will only work once the actual element your trying to select is inside the 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;
}

From above you can see that document is only being used after the window has loaded 从上面您可以看到文档仅在窗口加载后使用

Maybe you want to try: 也许你想尝试:

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

Then you can call it later, after the DOM loads. 然后,您可以在DOM加载后稍后调用它。

You need it in a function because otherwise JavaScript will try to calculate the value at definition time. 您需要在函数中使用它,否则JavaScript将尝试在定义时计算该值。

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

You could just scrap the prototype method altogether and set the property in the onload handler: 您可以完全废弃原型方法并在onload处理程序中设置属性:

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

Then, you would only set it once, but also guarantee the DOM will have loaded and the property will be valid by then. 然后,您只需设置一次,但也保证DOM将被加载,然后属性将有效。

What you had is equivalent to: 你拥有的相当于:

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();
}

The code that you posted works fine. 您发布的代码工作正常。 Are you sure you have an element whose id is wrapper? 你确定你的id是包装的元素吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM