繁体   English   中英

无法获取JavaScript检查空对象

[英]Can't get JavaScript to check for null objects

我真的不知道这是什么问题。 据我所知,代码很简单,应该可以正常工作。

          var Prices="";
          for (var PriceCount = 1; PriceCount <= 120; PriceCount++) {
              var CurrentPrice = "Price" + PriceCount;
              if (prevDoc.getElementById(CurrentPrice).value != null) {
                  if (Prices == "") {
                      Prices = prevDoc.getElementById(CurrentPrice).value;
                  } else {
                      Prices += "," + prevDoc.getElementById(CurrentPrice).value;
                  }
              } else {
                  break;
              }
          }

表单上最多可以包含120个隐藏的输入。 当我们检查不存在的输入时,循环应该中断。 我的测试页有两个输入元素。 在第三个(空值)中,我在萤火虫中收到此错误:

prevDoc.getElementById(CurrentPrice) is null

 if (prevDoc.getElementById(CurrentPrice).value != null) {

是的,它为空...这就是ಠ_ಠ的检查内容

有人知道我在做什么错吗? 这似乎应该很简单。

编辑:为清楚起见,prevDoc = window.opener.document

if (prevDoc.getElementById(CurrentPrice).value != null) {

可以扩展为:

var element = prevDoc.getElementById(CurrentPrice);    
var value = element.value; /* element is null, but you're accessing .value */

if (value != null) { 

值永远不会为空。

如果未填写,则该值为“”或长度为零。

如果该元素不存在,则将检查该元素是否存在。

var CurrentPrice = "Price" + PriceCount;
var elem = prevDoc.getElementById(CurrentPrice);
if (elem && elem.value != null) {

尝试

if (prevDoc.getElementById(CurrentPrice) !== null)

我认为应该是:

var Prices="";
for (var PriceCount = 1; PriceCount <= 120; PriceCount++) {
    var CurrentPriceId = "Price" + PriceCount,
        CurrentPrice = prevDoc.getElementById(CurrentPriceId);

    if (CurrentPrice != null) {
        Prices = (Prices == "") ? CurrentPrice.value : (Prices + "," + CurrentPrice.value);
    }
    else break;
}

暂无
暂无

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

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