【问题标题】:Uncaught TypeError: Cannot read property 'addEventListener' of null未捕获的类型错误:无法读取 null 的属性“addEventListener”
【发布时间】:2020-08-13 05:02:34
【问题描述】:

我有一个代码 2 使用颜色和值过滤表(参考 stackoverflow),但出现错误

未捕获的类型错误:无法读取 null 的属性“addEventListener”。

它显示了这个错误。

$(document).ready(function(){
 $('#load_data').click(function(){
  $.ajax({
   url:"OutputNew.csv",
   dataType:"text",
   success:function(data){
    var employee_data = data.split(/\r?\n|\r/);
    var table_data = '<button onclick="javascript:demoFromHTML()">PDF</button><input type="text" id="myInput" name="myInput" placeholder="color"><br><input type="text" id="myInputtext" name="myInput" placeholder="First Name"><br><div id="VMTable"><table id="myTable" class="table table-striped"">';
    // var table_data = '<input type="text" id="myInput" name="myInput" placeholder="color"><br><input type="text" id="myInputtext" name="myInput" placeholder="First Name"><br><table id="myTable" class="table table-striped"">';
    for(var count = 0; count<employee_data.length; count++) {
     var cell_data = employee_data[count].split(',');
     table_data += '<tr>';
     for(var cell_count=0; cell_count<cell_data.length; cell_count++){
      if(count === 0){
       table_data += '<th>'+cell_data[cell_count]+'</th>';
      }else{
          if(cell_data[cell_count] .includes("Not Matching")){
                var ret = cell_data[cell_count].replace('Not Matching','');
                if (ret == ""){
                  table_data += '<td>'+ret+'</td>'
                }else{
                  table_data += '<td data-color="red"><span class="badge-danger">'+ret+'</span></td>'
                }
          }else if(cell_data[cell_count] .includes("Matching")){
                var ret = cell_data[cell_count].replace('Matching','');
                if (ret == ""){
                  table_data += '<td>'+ret+'</td>'
                }else{
                  table_data += '<td data-color="green"><span class="badge-complete">'+ret+'</span></td>';
                }
          }else{
              table_data += '<td>'+cell_data[cell_count]+'</td>';
          }
      }
     }
     table_data += '</tr>';
    }
    table_data += '</table>';
    
    $('#employee_table').html(table_data);
   }
  });   
 }); 
});
function myFunction() {
  // Declare variables
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("myInputtext");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        if (tr[i].style.display !== "none") {
          tr[i].style.display = "";
        }
      } else {
        tr[i].style.display = "none";
      }
    }
  }
  
if (filter==="") {
document.getElementById("myInput").value="";
document.getElementById("myInputtext").value="";
[...document.querySelectorAll("#myTable tbody tr")].forEach(el => { el.style.display = "" });
}
}





function filterTable(event) {
  var filter = document.getElementById("myInput").value.toUpperCase();
  var rows = document.querySelector("#myTable tbody").rows;

  if (filter === "RED" || filter === "R" || filter === "RE") {
    filter = "badge-danger";
  } else if (filter === "GREEN" || filter === "G" || filter === "GR" || filter === "GRE" || filter === "GREE") {
    filter = "badge-complete";
  }

  for (var i = 0; i < rows.length; i++) {
    var Col1 = rows[i].cells[0].innerHTML;
    var Col2 = rows[i].cells[1].innerHTML;
    var Col3 = rows[i].cells[2].innerHTML;
    if (Col1.indexOf(filter) > -1 ||
      Col2.indexOf(filter) > -1 ||
      Col3.indexOf(filter) > -1) {
      if (rows[i].style.display !== "none") {
        rows[i].style.display = "";
      }
    } else {
      rows[i].style.display = "none";
    }
  }
if (filter==="") {
document.getElementById("myInput").value="";
document.getElementById("myInputtext").value="";
[...document.querySelectorAll("#myTable tbody tr")].forEach(el => { el.style.display = "" });
}    
}

document.querySelector('#myInputtext').addEventListener('keyup', myFunction, false);
document.querySelector('#myInput').addEventListener('keyup', filterTable, false);

        function demoFromHTML() {
            var pdf = new jsPDF('p', 'pt', 'letter');
            source = $('#VMTable')[0];
            specialElementHandlers = {
                '#bypassme': function(element, renderer) {
                    return true
                }
            };
            margins = {
                top: 80,
                bottom: 60,
                left: 40,
                width: 522
            };
            // all coords and widths are in jsPDF instance's declared units
            // 'inches' in this case
            pdf.fromHTML(
                    source, // HTML string or DOM elem ref.
                    margins.left, // x coord
                    margins.top, {// y coord
                        'width': margins.width, // max width of content on PDF
                        'elementHandlers': specialElementHandlers
                    },
            function(dispose) {
                // dispose: object with X, Y of the last line add to the PDF 
                //          this allow the insertion of new lines after html
                pdf.save('Test.pdf');
            }
            , margins);
        }
<!DOCTYPE html>
<html>
 <head>
 <style>
div#loadbutton {
  margin-left: 158px;
}

h1#Heading {
  margin-left: 154px;
}

td {
  border: 1px solid black;
  word-wrap: break-word;
}

.table-responsive {
  min-height: .01%;
  overflow-x: auto;
  WIDTH: 223%;
  MARGIN-LEFT: -205PX;
}

.badge-Nill {
  display: inline-block;
  min-width: 49px;
  padding: 9px 9px;
  font-size: 12px;
  font-weight: 700;
  line-height: 1;
  color: #fff;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  background-color: blue;
  border-radius: 10px;
  width: 127px;
}

.badge-danger {
  display: inline-block;
  min-width: 49px;
  padding: 9px 9px;
  font-size: 12px;
  font-weight: 700;
  line-height: 1;
  color: #fff;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  background-color: red;
  border-radius: 10px;
  width: 127px;
}

th {
  text-align: left;
  width: 152px;
}

table {
  border-collapse: collapse;
  table-layout: fixed;
  width: 310px;
}

table td {
  border: solid 1px #fab;
  width: 100px;
  word-wrap: break-word;
}

.badge-complete {
  display: inline-block;
  min-width: 49px;
  padding: 9px 9px;
  font-size: 12px;
  font-weight: 700;
  line-height: 1;
  color: #fff;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  background-color: limegreen;
  border-radius: 10px;
  width: 127px;
}
h1#Heading {
    margin-left: 154px;
    margin-top: -44px;
}
div#employee_table {
  margin-left: 170px;
  margin-right: 70px;
}

 </style>
  <link rel = "icon" href = "https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200X200.png" type = "image/x-icon"> 
  <title>TValidator</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="jspdf.debug.js"></script>

  
 </head>
 <body>
  <div class="container">
   <div class="table-responsive">
   <!-- <img src="banner.png" id="banner"> -->
    <h1 id ="Heading">Validator</h1>
    <br />
    <div id ="loadbutton">
     <button type="button" name="load_data" id="load_data" class="btn btn-info">Load Data</button>
     
    </div>
    <br />
    <div id="employee_table">
    </div>
    </div>
   </div>
  </div>
 </body>
</html>

这里是 output.csv

Application,FileName,ADG,KLHJ,POWB
ads,FileName1,jhjkhkjhMatching,jhjkhkNot Matching,jhjkhkjhMatching
adr,FileName2,databaseMatching,databaseMatching,databaseMatching
popo,FileName3,POEBMatching,POEBMatching,POEBMatching

所以这里它告诉我添加偶数侦听器,我不知道在此代码中在哪里添加事件侦听器。因为表是基于 csv 动态创建的,并且在加载按钮单击表之后,然后对表进行过滤(需要事件侦听器)。

所以请帮我添加事件监听器

【问题讨论】:

    标签: javascript jquery filter


    【解决方案1】:

    尝试在页面加载后添加事件侦听器。尝试附加事件侦听器时,无法找到 id 为“myInputtext”的元素。

    由于添加事件侦听器是在任何函数之外完成的,因此在导入脚本时,它会尝试添加事件侦听器,但由于找不到,因此会引发错误。

    【讨论】:

    • 你能解释一下在哪里添加事件监听器以及如何添加
    • window.onload = function(){ //code for adding the event listener }
    【解决方案2】:

    Uncaught TypeError: Cannot read property 'addEventListener' of null 表示您正在尝试将事件侦听器添加到不存在的元素。如果您正在侦听的元素被烘焙到 HTML 代码中(意味着它在页面加载时就存在),请确保您的事件侦听器正在等待 DOM 内容首先加载:

    window.addEventListener('DOMContentLoaded', (event) => {
        // My Code
    });
    

    如果您正在侦听的元素是使用 Javascript 动态创建的,请在创建元素后添加侦听器。 (首先创建元素并将其附加到 DOM,然后为元素添加监听器)

    最后,您可能已经删除了该元素,因此请在侦听事件之前检查该元素是否存在。

    如果您仍然遇到问题,也许可以尝试一下,以便我们可以试用您的代码。

    【讨论】:

    • 所以这里的表格或元素是在单击按钮后加载的。所以可以解释我在哪里添加它
    • 您需要找到加载该元素的代码,并在创建该元素后立即添加一个事件侦听器。因此,如果您有一个名为makeTable() 的函数,请确保在该函数中包含该表元素的事件侦听器。当您尝试创建事件侦听器时,它会查找元素,然后尝试添加事件侦听器。如果该元素尚不存在,则会引发错误,因此请确保在页面上存在该元素之后创建事件侦听器。
    • 我刚刚更新了代码,所以事情是我的表格是通过按钮加载的,而事件监听器实际上用于过滤表格。 (有问题),所以你是说我必须在创建期间或过滤期间将其添加到表中
    • 是的,我刚刚创建了一个小提琴,你现在能帮帮我吗,我不知道在哪里添加它
    猜你喜欢
    • 1970-01-01
    • 2021-03-07
    • 2015-05-11
    • 2020-12-31
    • 1970-01-01
    • 2022-01-20
    • 2021-12-31
    • 2021-11-18
    • 1970-01-01
    相关资源
    最近更新 更多