简体   繁体   English

JavaScript中getelementbyid的多个if-or语句

[英]Multiple if-or statement for a getelementbyid in JavaScript

I am trying to ensure that the information put into a field is not null, of a certain length and does not contain letters. 我试图确保放入字段中的信息不为null,具有一定长度,并且不包含字母。

var Xlength = document.getElementById('X')
if( document.getElementById('X').value === '' || Xlength.innerHTML.length != 16 || isNaN(Xlength) )

When I test the code however, it always comes up as false. 但是,当我测试代码时,它总是出现为false。 Is there a simple syntax issue in this question, or am I misunderstanding something more crucial? 这个问题是否有一个简单的语法问题,还是我误解了一些更关键的东西?

Assuming X is an input field, then var Xlength = document.getElementById('X') will select this input field. 假设X是输入字段,则var Xlength = document.getElementById('X')将选择此输入字段。 This variable isn't named well in that case, since it's the field itself, and not the length of whatever input it contains. 在这种情况下,此变量的名称不正确,因为它是字段本身,而不是它包含的任何输入的长度。

document.getElementById('X').value === '' will be false if there is something entered in the field, because it will not be empty. 如果在字段中输入了某些内容,则document.getElementById('X').value === ''将为false,因为它不会为空。

Xlength.innerHTML.length != 16 isn't meaningful, because there is no innerHTML; Xlength.innerHTML.length != 16没什么意义,因为没有innerHTML。 what you really want is Xlength.value.length . 您真正想要的是Xlength.value.length Furthermore, Xlength.value.length != 16 evaluates to true if length <= 15 or length >= 17 , which is also probably not what you really want, so I would adjust this equality check to something like Xlength.value.length < 16 此外,如果length <= 15length >= 17 ,则Xlength.value.length != 16计算结果为true ,这可能也不是您真正想要的值,因此我将这种相等性检查调整为Xlength.value.length < 16

isNaN(Xlength) is not meaningful to include. isNaN(Xlength)没有意义。

I would rewrite this as: 我将其重写为:

var Xval = document.getElementById('X').value;
    // or, optionally
var Xval = document.getElementById('X').value.trim();
    // removes extra white space
if(Xval.length > 0 && Xval.length < 16){
    // is not empty and less than 16 characters
}

When you write like this: 当您这样写时:

document.getElementById('X'), it doesn't mean any length it means a DOM element. document.getElementById('X'),它并不意味着任何长度,它意味着DOM元素。

so isNaN(Xlength) will always be true 所以isNaN(Xlength)将始终为true

Also, document.getElementById('X').value this will be undefined always because there is no 'value' on DOM element. 另外, document.getElementById('X')。value始终是不确定的,因为DOM元素上没有“值”。

Here, Xlength.innerHTML.length != 16 may be false because the content may not be 16 for this element 此处,Xlength.innerHTML.length!= 16可能为false,因为此元素的内容可能不是16

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

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