使用变量源时无法设置 null 的 属性 'src'

Cannot set property 'src' of null when using variable source

我看到这个问题被问了很多次,我一直在寻找每一个问题的解决方案,但找不到适合我的具体问题的解决方案。我正在使用不同的字符串和变量组成 link,我想用图像填充 table。到目前为止,在大多数解决这个问题的线程中,我可以看到以下策略:

document.getElementById('ID').src = variablewithlink;

甚至这样:

document.querySelector('img').src = variablewithlink;   

插入 html 为:

<img id="ID" src="" width="100" height="70";/>  

这就是我在代码中使用的内容,但它仍然提供

Uncaught TypeError: Cannot set property 'src' of null

当我使用 alert 记录变量时,它显示包含图像的 links,但是当在 <img> 标签中读取它时,它给出了那个错误.谁能帮我弄清楚我做错了什么?代码如下:

<html>

<body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://www.gstatic.com/firebasejs/4.1.2/firebase.js"></script>
  <script>
    var config = {
      apiKey: "AIzaSyCg9wsEL5tAYdSyz9IapqvvMGWpFNAlc74",
      authDomain: "checkup-7b62e.firebaseapp.com",
      databaseURL: "https://checkup-7b62e.firebaseio.com",
      projectId: "checkup-7b62e",
      storageBucket: "checkup-7b62e.appspot.com",
      messagingSenderId: "324802643995"
    };
    firebase.initializeApp(config);
  </script>

  <head>
  </head>
  <table style="width:100%" id="ex-table">
    <tr id="tr">
      <th>Image</th>
      <th>Text</th>
  </table>

  <script>
    var database = firebase.database();
    database.ref("-Events").orderByKey().limitToLast(5).once('value', function(snapshot) {
      if (snapshot.exists()) {
        content = '';
        snapshot.forEach(function(data) {
          val = data.val();
          link_for_picture = "https://firebasestorage.googleapis.com/v0/b/checkup-7b62e.appspot.com/o/" + val.imageUrl.split("/")[3] + "?alt=media";
          document.getElementById('image').src = link_for_picture;
          alert(link_for_picture);
          content += '<tr>';
          content += '<td>' + '<img id="image" src=link_for_picture border={0} height={150} width={150}></img>' + '</td>';
          content += '<td>' + val.headline + '</td>';
          content += '</tr>';
        });
        $('#ex-table').append(content);
      }
    });
  </script>

</body>

</html>

  1. 您忘记连接变量 <img id="image" src='+link_for_picture+' border={0}。使用 template literals 将防止此类错误。
  2. 您有 src of null 错误,因为您试图在 img 之前 附加它到 HTML。
  3. 最后也是最常见的菜鸟错误:在该循环中,您创建了多个具有相同 ID 的元素。但是id必须是唯一的。

这里是 http://jsfiddle.net/Smollet92/dwx1mb4a/4/(因为 SO 片段出于某种原因给出了脚本错误)

如果您尝试为尚未构建的 属性 赋值,也可能会发生这种情况。将脚本 link 放在而不是之前将解决问题。