首页 > 解决方案 > 检查 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';

我将如何检查属性是否实际设置,如果没有,我可以继续,那么我想为代码选择替代课程。

感谢您的帮助和所花费的时间。

标签: javascript

解决方案


如果您的元素具有由属性的存在/不存在确定的备用状态,则使用.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>


推荐阅读