JavaScript - 如果语句总是返回true

Bry*_*yan 0 javascript if-statement

我有一些JavaScript,我想在HTML中搜索一个类名,然后检测该div中几个元素的高度,将它们添加到一起,并在警报中显示总高度.以下代码似乎运行完美,但我注意到代码将运行,无论类名是什么,即使HTML中不存在该类.如何重写if语句,以便只有在遇到具有指定类名的div时才运行代码?我不希望它检测错误的h1和p元素的高度.谢谢你的帮助.

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>
Run Code Online (Sandbox Code Playgroud)

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();
Run Code Online (Sandbox Code Playgroud)

Tha*_*you 10

即使您的文档查询返回一个空数组,它仍然是 true

这是因为它[]是一个"真实"的价值.

if ([]) { console.log("always true"); }
Run Code Online (Sandbox Code Playgroud)

而是试试

var elems = document.getElementsByClassName("foo");

if (elems.length > 0) {
  // ...
}
Run Code Online (Sandbox Code Playgroud)

如果您不想访问elems后者,可以跳过中间变量

if (document.getElementsByClassName("foo").length > 0) // ...
Run Code Online (Sandbox Code Playgroud)

根据你的评论

var div = document.getElementsByClassName("testing");

if (div.length > 0) {
  div[0].getElementsByTagName("h1")[0] ...
  div[0].getElementsByTagName("p")[0] ...
}
Run Code Online (Sandbox Code Playgroud)

这将在上下文中找到标记div而不是全局document上下文.