未捕获的TypeError: Cannot read property 'textContent'的定义

Uncaught TypeError: Cannot read property 'textContent' of undefined

本文关键字:定义 textContent property Cannot TypeError read      更新时间:2023-09-26

当我点击日期值我有这个"错误未捕获的类型错误:无法读取未定义的属性'textContent' "

这是我的代码,你能帮我确定错误的来源,我如何纠正这个

<?php
while($row = mysqli_fetch_array($query)){
                                    $date = $row['Date'];
                                    $time = $row['Time'];
                                    $latitude= $row['Latitude'];
                                    $longitude= $row['Longitude'];
                                    $depth =$row['Depth'];
                                    $magnitude = $row['Magnitude'];
                                    //$array_lat_lon[] = $lat = $row['LAT'];
                                    //$array_lat_lon[] = $lon = $row['LON'];
                                $the_arraypei[] = array($row['Date'] ); //added
                                //$the_array[] = array($row['LAT']."" , "".$row['LON']) ;      
                                //$timestamp = strtotime()
                                echo '<tr class="normalRow"><td id="date2"><a href="#" onClick="functiontoget(''$date'');">'.$date.'</a></td><td border="1">'.$time.'</td><td border="1">'.$latitude.'</td><td border="1">'.$longitude.'</td><td border="1">'.$depth.'</td><td border="1">'.$magnitude.'</td></tr>';

                                                                }?>
   <script>
     function functiontoget($date) { 
     var x = document.getElementsByTagName("#date")[0].textContent;
     document.getElementById("demo").innerHTML = x;}
     </script>
     <p id="demo"></p>

如果您想通过标签名称查询元素,您可以使用getElementsByTagName,但是您有一个名为#date的标签吗?#date是一个元素的id,你需要使用getElementById

修改你的javascript代码:

function functiontoget($date) { 
   var x = document.getElementById("date").textContent;
   document.getElementById("demo").innerHTML = x;
}

这是我的代码。

问题是,当我单击表中的第一个value($date)时,出现了警报,但当我单击另一个value($date)时,没有出现警报。

就像唯一可点击的是第一个value($date)

<?php 
  while($row = mysqli_fetch_array($query)){
    $date = $row['Date'];
    $time = $row['Time'];
    $latitude= $row['Latitude'];
    $longitude= $row['Longitude'];
    $depth =$row['Depth'];
    $magnitude = $row['Magnitude'];
    echo '<tr class="normalRow"><td id="date2">'.$date.'</td><td border="1">'.$time.'</td><td border="1">'.$latitude.'</td><td border="1">'.$longitude.'</td><td border="1">'.$depth.'</td><td border="1">'.$magnitude.'</td></tr>';
  }}
  }
?>
<script>
  $(document).ready(function() {
    $("#date2").click(function() {
      var x = $(this).text();
      alert(x);
      x = $(this).next().html();
      alert(x);
      ...
    });
  });
 </script>