检查getAttribute是否未定义

时间:2019-06-04 10:33:41

标签: javascript

当前,我的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';

我将如何检查该属性是否设置正确,如果没有设置,我可以继续进行操作,我想为代码选择替代方法。

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

4 个答案:

答案 0 :(得分:0)

evt.target未定义,这意味着您需要在尝试getAttribute()之前进行检查。这是您可以选择的选项之一,主要取决于您的“代码替代课程”是什么:

var appName; 
    if(evt && evt.target && ( evt.target.getAttribute("appName") != "" || evt.target.getAttribute("appName") != null )){
        appName = evt.target.getAttribute("appName");
    }

答案 1 :(得分:0)

您可以通过执行以下操作检查是否有未定义的内容(从here复制):

if(typeof obj !== "undefined") {
    // obj is a valid variable, do something here.
}

请注意,typeof始终返回一个字符串。另外,与“双重等于”和“三重等于”进行比较之间也存在差异,因此您可能需要检查this

答案 2 :(得分:0)

我提供了示例代码段。

  

您尝试过evt.target.getAttribute而不是evt.getAttribute

尝试这样。

function findAttr(e){
  if (!e.hasAttribute("appName")) {
    console.log("No attribute");
  } else {
    console.log(e.getAttribute("appName"));
  }
  
}
<div onclick="findAttr(this)">is attr present?</div>
<div onclick="findAttr(this)" appName="test">is attr present?</div>

答案 3 :(得分:0)

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

相关问题