2015-05-28 41 views
0

我是JavaScript新手,正在练习。我试图显示具有类名“test”的div内的h1和p元素的组合高度。我查了各种各样的东西,觉得我真的很接近,但无法完成这个工作。任何人都可以帮忙?JavaScript - 如果语句使用.offsetHeight不起作用

HTML:

<div class="test"> 
    <h1>Understanding Scope</h1> 
    <p>By understanding code's <em>scope</em>, we know when that code affects only one part of our code, or the entire codebase. If we create things that are <em>global</em> in scope, we are giving any code the supreme power to control our code. So we want to protect our code by being very careful when creating things that are global in scope. This is especially important if you plan on using JavaScript libraries like jQuery.</p> 
</div> 
<h1>Local Scope</h1> 
<p>JavaScript uses <em>function scope</em>, meaning every time we create a new function the scope changes. Any code inside that function is <em>local</em> to that function. Code that is local in scope is not accessible to outside code.</p> 

的JavaScript:

function testing(){ 
    if (document.getElementsByClass('test')){ 
     var headerHeight = document.getElementsByTagName('h1').offsetHeight; 
     var textHeight = document.getElementsByTagName('p').offsetHeight; 
     var totalHeight = headerHeight + textHeight; 

     alert(totalHeight); 
    } 
} 

testing(); 
+0

这是什么显示目前?你在哪里包括JavaScript(内联或外部)? – Brennan

+0

'document.getElementsByClass'和'document.getElementsByTagName'返回NodeLists - 您必须通过类似数组的索引访问它们中的特定项目,然后才能访问它们的属性。此外,您可能会提前调用函数(在这些元素存在之前),具体取决于它究竟在哪里/如何嵌入。 – CBroe

+0

我有一个外部JavaScript文件。如果我抛出警报(“测试”);在函数内部,但在if语句之前,它将显示该警报,但不是我期望得到的另一个警报。如上面的代码,它显示HTML,但没有警报。 – Bryan

回答

0

这是document.getElementsByClassName,不getElementsByClass,H1和P标签还你得到阵列

function testing(){ 
    if (document.getElementsByClassName('test')){ 
     var headerHeight = document.getElementsByTagName('h1')[0].offsetHeight; 
     var textHeight = document.getElementsByTagName('p')[0].offsetHeight; 
     var totalHeight = headerHeight + textHeight; 

     alert(totalHeight); 
    } 
} 

testing(); 
+0

啊,忘记名字很好。这似乎工作。谢谢! – Bryan

0
function testing(){ 
    if (document.getElementsByClassName('test')){ 

     var headerHeight = document.getElementsByTagName('h1')[0].offsetHeight; 
     var textHeight = document.getElementsByTagName('p')[0].offsetHeight; 
     var totalHeight = headerHeight + textHeight; 

     alert(totalHeight); 
    } 
} 

testing();

+0

这工作。谢谢! – Bryan