简体   繁体   English

if(document.getElementById('something')!= null)是否与if(document.getElementById('something'))相同?

[英]Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

When I want to check if an element exists in a page. 当我想检查页面中是否存在元素时。 Are these two checks the same? 这两个检查是否相同? Is there a better more compact way to check the existence? 有没有更好的更紧凑的方式来检查存在?

What if I want to check if the value == '' . 如果我想检查value == ''该怎么办? Can this be included in this check as well? 这也可以包含在此检查中吗?

A reference to an element will never look "falsy", so leaving off the explicit null check is safe. 对元素的引用永远不会显示为“falsy”,因此不使用显式null检查是安全的。

Javascript will treat references to some values in a boolean context as false : undefined, null, numeric zero and NaN , and empty strings. Javascript会将对布尔上下文中某些值的引用视为false :undefined,null,numeric zero和NaN以及空字符串。 But what getElementById returns will either be an element reference, or null. getElementById返回的内容将是元素引用,或者为null。 Thus if the element is in the DOM, the return value will be an object reference, and all object references are true in an if () test. 因此,如果元素在DOM中,则返回值将是对象引用,并且在if ()测试中所有对象引用都为true If the element is not in the DOM, the return value would be null , and null is always false in an if () test. 如果元素不在 DOM中,则返回值将为null ,并且在if ()测试中null始终为false

It's harmless to include the comparison, but personally I prefer to keep out bits of code that don't do anything because I figure every time my finger hits the keyboard I might be introducing a bug :) 包含比较是无害的,但我个人更喜欢保留一些不做任何事情的代码,因为每当我的手指敲击键盘时我都会想到我可能会引入一个bug :)

Note that those using jQuery should not do this: 请注意,那些使用jQuery的人应该这样做:

if ($('#something')) { /* ... */ }

because the jQuery function will always return something "truthy" — even if no element is found, jQuery returns an object reference. 因为jQuery函数总会返回“truthy” - 即使没有找到任何元素,jQuery也会返回一个对象引用。 Instead: 代替:

if ($('#something').length) { /* ... */ }

edit — as to checking the value of an element, no, you can't do that at the same time as you're checking for the existence of the element itself directly with DOM methods. 编辑 - 关于检查元素的 ,不,你不能在你用DOM方法直接检查元素本身的存在的同时做到这一点。 Again, most frameworks make that relatively simple and clean, as others have noted in their answers. 同样,大多数框架使其相对简单和干净,正如其他人在他们的答案中所指出的那样。

It's better (but wordier) to use: 使用它更好(但更啰嗦):

var element = document.getElementById('something');
if (element != null && element.value == '') {
}

Please note, the first version of my answer was wrong: 请注意,我的答案的第一个版本是错误的:

var element = document.getElementById('something');
if (typeof element !== "undefined" && element.value == '') {
}

because getElementById() always return an object (null object if not found) and checking for "undefined" would never return a false , as typeof null !== "undefined" is still true . 因为getElementById()总是返回一个对象(如果没有找到空对象),并且检查"undefined"将永远不会返回false ,因为typeof null !== "undefined"仍然是true

Just do it like this: 就这样做:

if(!document.getElementById("someId") { / Some code. Note the NOT (!) in the expresion / }; if(!document.getElementById(“someId”){/ some code。注意expresion中的NOT(!) /};

If element with id "someId" does not exist expresion will return TRUE (NOT FALSE === TRUE) or !false === true; 如果id为“someId”的元素不存在,则expresion将返回TRUE(NOT FALSE === TRUE)或!false === true;

try this code: 试试这段代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="format-detection" content="telephone-no">
        <meta name="viewport" content="user-scalable=no, initial-scale=1, minimum-scale=1, maximum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi">
        <title>Test</title>
    </head>
    <body>
      <script>
var createPerson = function (name) {
    var person;
    if (!document.getElementById(name)) {
        alert("Element does not exist. Let's create it.");
      person = document.createElement("div");
//add argument name as the ID of the element
      person.id = name;
//append element to the body of the document
      document.body.appendChild(person);
    } else {
        alert("Element exists. Lets get it by ID!");
      person = document.getElementById(name);
    }
    person.innerHTML = "HI THERE!";

};
//run the function.
createPerson("someid");
          </script>
       </body>
</html>

Try this in your browser and it should alert "Element does not exist. Let's create it." 在你的浏览器中尝试这个,它应该警告“元素不存在。让我们创建它。”

Now add 现在添加

<div id="someid"></div>

to the body of the page and try again. 到页面正文,然后再试一次。 Voila! 瞧! :) :)

document.getElementById('something') can be 'undefined'. document.getElementById('something')可以是'undefined'。 Usually (thought not always) it's sufficient to do tests like if (document.getElementById('something')) . 通常(以为并非总是如此)只需执行if (document.getElementById('something'))

Yeah. 是啊。 Try this.. lazy evaluation should prohibit the second part of the condition from evaluating when the first part is false/null: 试试这个..懒惰的评估应该禁止条件的第二部分在第一部分为false / null时进行评估:

var someval = document.getElementById('something')
if (someval && someval.value <> '') {

jquery will provide you with this and more ... jquery将为您提供更多......

if($("#something").val()){ //do stuff}

It took me a couple of days to pick it up, but it provides you with you with so much more functionality. 我花了几天时间才拿起它,但它为您提供了更多功能。 An example below. 以下是一个例子。

jQuery(document).ready(function() {
    /* finds closest element with class divright/left and 
    makes all checkboxs inside that div class the same as selectAll...
    */
        $("#selectAll").click(function() {
        $(this).closest('.divright').find(':checkbox').attr('checked', this.checked);
    });
});

如果你只想从元素中获取.value ,最干净的版本特别好。

document.getElementById('elementsid') ? function_if_exists(); function_if_doesnt_exists();

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

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