javascript - 检查 getAttribute 是否未定义
问题描述
目前,我的 javascript 正在动态创建页面,因此当用户单击 X 时,将为该选项生成新的 html 代码,如果 B 则反之亦然。
虽然,我得到了“未定义”的错误。即使我确实在将变量传递给函数之前检查了它们。
我当前的非工作原型看起来像这样
var appName;
if(evt.target.getAttribute("appName") != "" || evt.target.getAttribute("appName") != null){
appName = evt.target.getAttribute("appName");
}
在此之前,我尝试过使用看起来像这样的东西
var appName = evt.target.get("appName");
if (typeof appName != typeof undefined && appName !== false) {
appName = evt.target.getAttribute("appName");
}
else appName = 'boo';
那仍然返回未定义。
最后,我尝试了或多或少相同的方法,但它仍然返回
Uncaught TypeError: Cannot read property 'getAttribute' of undefined
以下代码如下所示:
var appName = '';
if(evt.target.hasAttribute("appName")){
appName = evt.target.getAttribute("appName");
}
else appName = 'boo';
我将如何检查属性是否实际设置,如果没有,我可以继续,那么我想为代码选择替代课程。
感谢您的帮助和所花费的时间。
解决方案
如果您的元素具有由属性的存在/不存在确定的备用状态,则使用.toggleAttribute()
function editMode(e) {
const clicked = e.target;
const editor = document.querySelector('.editor');
if (clicked.matches('.mode')) {
clicked.classList.toggle('on');
clicked.classList.toggle('off');
editor.toggleAttribute('contenteditable');
if (clicked.matches('.off')) {
editor.focus();
} else {
editor.blur();
}
}
return false;
}
document.querySelector('.mode').onclick = editMode;
.editor {
min-height: 32px
}
.mode {
float: right;
display: inline-block;
width: 100px;
}
.on::before {
content: 'READ/WRITE';
}
.off::before {
content: 'READ ONLY';
}
<fieldset class='editor'></fieldset>
<button class='mode on'></button>
推荐阅读
- python - 在 ssh 终端中引发 Python Selenium“连接被拒绝”错误,但在常规终端中没有
- r - 使用 RMySQL 未知数据库连接到 MySQL 数据库
- c# - XML反序列化在第一个元素之后不起作用
- ruby-on-rails - AWS:S3 Bucket AWS 您无法授予公共访问权限,因为此账户的阻止公共访问设置已打开
- vue.js - 使用 WebpackDevMiddleware 404s 的客户端深度链接
- python - 如何从当前位置移动按钮
- javascript - 通过在 onClick 期间传递参数来使用 window.open(param,'_blank') 以响应在新选项卡中打开页面是否安全?
- hosting - 是否可以将我的域名转发到免费托管网站?
- arrays - 将函数应用于 Julia 中的列对
- async-await - Webdriverio 等到可见