javascript - 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 语句中遗漏了什么?
解决方案
您可能只想做一个简单的检查以查看您的元素是否存在。在这个例子中,如果它不存在,我已经设置了一些默认文本。根据您的逻辑需要,默认值也可以设置为空白或空。
element = document.querySelector('your_selector');
var some_variable = element ? element.innerText : 'some_default_text';
推荐阅读
- maven - 使用 Maven 在 WebSphere Liberty 19.0.0.8 服务器中实现 CI/CD
- android - 向具有 root 访问权限的第三方应用授予不可更改的权限
- python - Pyhonic 使用 if 语句来处理应用于分块列表的不等式
- c++ - 我收到以下代码的运行时错误 SIGCONT
- vim - VS代码VIM扩展复制粘贴
- python - 神经网络总是预测同一个类别
- android - 在 Nougat 上使用谷歌助手停止/暂停 Spotify 有什么问题吗?
- python - AWS - Lambda 无法通过 Python SDK 调用另一个 lambda
- python - 将内容从 .txt 文件复制到 Excel 文件,并粘贴到最后一行的下方
- c - 这个函数使用 RECURSION 删除给定数组中的所有强数字的错误是什么?