首页 > 解决方案 > If Else 语句中断,因为变量并不总是存在

问题描述

我正在 Google 跟踪代码管理器中创建一个自定义 javascript 变量,它应该注册特定的按钮点击并将另一个字段/标题文本作为变量传回。

我在下面找到的代码的问题是 mapButtonText 变量并不总是存在(您必须单击地图图标才能存在),直到那时我在 chrome 中转到开发人员控制台并查找 mapButtonText all我得到的回报是:

Uncaught TypeError: Cannot read property 'innerText' of null at <anonymous>:1:124

此外,当 else if 语句到达 mapButtonText 条件时,它会破坏整个 if else 语句(这意味着即使是第一个语句也不会再返回正确的值)。

function(){
  
  var formButtonText = document.querySelector("#locationSelect > button").innerText;
  var formSelectedLocation = document.querySelector('#locationID option').innerText;
  var mapButtonText = document.querySelector("#map > div > div > div > div > div > div > div > div > div > div > div > div > div.infoWindow > a").innerText;
  var mapSelectedLocation = document.querySelector('.infoWindow:hover h3').innerText;
  var clickLocationName;
  var clickElementText = {{Click Text}};

  if (clickElementText === formButtonText){
    clickLocationName = formSelectedLocation;
  }
  else if (clickElementText === mapButtonText){
    clickLocationName = mapSelectedLocation;
  }
  else {clickLocationName = "No Location Selected";}

  return clickLocationName;

}

我已经测试了排除 else if 行并且代码工作正常(见下面的代码)

function(){
  
  var formButtonText = document.querySelector("#locationSelect > button").innerText;
  var formSelectedLocation = document.querySelector('#locationID option').innerText;
  var mapButtonText = document.querySelector("#map > div > div > div > div > div > div > div > div > div > div > div > div > div.infoWindow > a").innerText;
  var mapSelectedLocation = document.querySelector('.infoWindow:hover h3').innerText;
  var clickLocationName;
  var clickElementText = {{Click Text}};

  if (clickElementText === formButtonText){
    clickLocationName = formSelectedLocation;
  }
  else {clickLocationName = "No Location Selected";}

  return clickLocationName;

}

为了使第一段代码工作,我在 else if 语句中遗漏了什么?

标签: javascriptif-statementgoogle-tag-manager

解决方案


您可能只想做一个简单的检查以查看您的元素是否存在。在这个例子中,如果它不存在,我已经设置了一些默认文本。根据您的逻辑需要,默认值也可以设置为空白或空。

   element = document.querySelector('your_selector');
   var some_variable = element ? element.innerText : 'some_default_text';

推荐阅读