简体   繁体   English

不能使用 If - Else 元素存在于 Javascript

[英]can't use If - Else element exists in Javascript

I wrote a JS function to create a table in html and JS I want to click submit and after that the table to be created but I dont want the Submit button to create another table if clicked again I tried to use IF - Else statements in the function but It's not working我写了一个 JS function 在 html 和 JS 中创建一个表我想单击提交,然后创建该表,但如果再次单击我不希望提交按钮创建另一个表我尝试在function 但它不工作

code:代码:

Button:按钮:

 document.getElementById("btn_submit").addEventListener("click",sizeGrid)

function function

 function makeGrid(x,y) {
    event.preventDefault();
    if (document.getElementById('tbl') != null)
      {
        return;
      }
      else
      {
        var body = document.getElementById('pixelCanvas');
        var tbl  = document.createElement('table');
        for(var i = 0; i < x; i++){
           var tr = tbl.insertRow();
            for(var j = 0; j<y; j++){
              var td= tr.insertCell()
           }

        }

         body.append(tbl);
         paint()
      }

      }

HTML HTML

    <h2>Design Canvas</h2>
<table  id="pixelCanvas">
</table>

The table gets created two times after I click submit two times单击两次提交后,表被创建了两次

You should set the tbl 's id to 'tbl' by tbl.id = 'tbl' .您应该通过tbl.id = 'tbl' tbl 'tbl'

You are doing the check on the id of the table but never assign one.您正在检查表的 id,但从未分配一个。

function makeGrid(x,y) {
  event.preventDefault();
  if (document.getElementById('tbl') != null) {
    return;
  } else {
    var body = document.getElementById('pixelCanvas');
    var tbl  = document.createElement('table');
    tbl.id = "tbl"; // Assign the id for the check
    for(var i = 0; i < x; i++){
      var tr = tbl.insertRow();
      for(var j = 0; j<y; j++){
        var td= tr.insertCell()
        }
    }
    body.append(tbl);
    paint();
  }

};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM