更改按钮功能时出现未捕获参考错误

时间:2017-03-21 03:38:31

标签: javascript html

当元素有子节点时,我试图让按钮显示模态。所以当你点击它时,它会激活该功能并相应地显示模态,它会通过添加id" myBtn"到button元素。

这是我的HTML:

<li id='parentNode'>
  <button onclick="child_check()" id="button" class='customer-btn'><a href='#'>Customer 6</a></button>
  <ul>
    <li id='childNode'>
      <a href='#'>Customer A</a>
    </li>
  </ul>
</li>

这是我的JS:

<script>

    var modal = document.getElementById('myModal');
    // Get the button that opens the modal
    var btn = document.getElementById(" myBtn");
    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];
    btn.onclick = function() {
       modal.style.display = "block";
    }


    // When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
  }
    // When the user clicks anywhere outside of the modal, close it

// Check to see if the list element has a child
function child_check() {
  var child = document.getElementById("childNode");
  var parent_check = document.getElementById("parentNode").contains(child);
  var parent = document.getElementById("parentNode")
  var button = document.getElementById("button")
  if (parent_check){
    button.id += " myBtn";
    // Code that activates modal
    // Get the modal

    // When the user clicks on the button, open the modal 

  }
}


</script>

有任何帮助吗?我离开这里

修改:似乎正在运行,仍然收到以下错误:Uncaught TypeError: Cannot read property 'contains' of null at child_check (profile:259)

1 个答案:

答案 0 :(得分:1)

除了模态(我在这里看不到模态代码),您可以像这样在+= " myBtn"行添加一个空格,以便成功地为按钮添加ID为'myBtn'。如果没有,只需使用简单的“=”并为其提供所需的所有ID,用空格分隔。