我有一些JavaScript,我想要在HTML中搜索類名稱,然後檢測該div內的幾個元素的高度,將它們加在一起,並顯示總高度一個警報。下面的代碼似乎完美運行,但我注意到代碼將運行,無論類名是什麼,即使該類不存在於HTML中。我怎樣才能重寫if語句,以便它只會在代碼碰到具有指定類名的div時才運行代碼?我不希望它檢測到錯誤的h1和p元素的高度。謝謝你的幫助。JavaScript - 如果語句總是返回true
HTML:
<div class="testing">
<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.getElementsByClassName('testing')){
var headerHeight = document.getElementsByTagName('h1')[0].offsetHeight;
var textHeight = document.getElementsByTagName('p')[0].offsetHeight;
var totalHeight = headerHeight + textHeight;
alert(totalHeight);
}
}
testing();
這似乎只是檢查該分區是否存在,然後繼續看整個的第一h1和p元素的高度文件。我希望它嚴格從該div中尋找第一個h1和p元素。 – Bryan
@Bryan,我提供了一個編輯來解決您的評論 – naomik