如何显示涉及JavaScript变量的图像

时间:2017-06-24 17:19:37

标签: javascript html image

我有一张桌子,我想在其中一个单元格中显示图像。

用户使用提示符()输入一个数字,我希望他们输入的数字构成图像网址的一部分。

我在这段代码中如何/在哪里显示图片网址?

<td><script>

    var userID = prompt("Enter the ID of the user you want to search for.");

    var userImage = "https://storage.brick-hill.com/images/avatars/" + userID + ".png";

</script></td>

2 个答案:

答案 0 :(得分:0)

<table cellpadding="0" cellspacing="">

您已为表列分配了Id,并编写了一个函数以在相应的行上显示图像。

希望这会有所帮助..!

答案 1 :(得分:0)

放置图片有两种选择:

  1. 有一个<img>元素(尚未配置src,默认情况下设置为隐式)已经存在于HTML中,但不要t显示它,直到JavaScript建立了图像路径,并且客户端已完全下载图像(这可确保用户不会看到部分图像)。
  2. &#13;
    &#13;
    var userID = prompt("Enter the ID of the user you want to search for. \nFor this test, enter 169");
    
    // Get a reference to the placeholder:
    var placeholder = document.getElementById("placeholder");
    
    // Set up a load event handler that will unhide the image once its loaded
    placeholder.addEventListener("load", function(){
      this.classList.remove("hidden");
    });
    
    // Update the source of that image (which will cause the load event to trigger)
    placeholder.src = "http://i2.cdn.cnn.com/cnnnext/dam/assets/150409124320-20-cnnphotos-hubble-restricted-super-" + userID + ".jpg";
    &#13;
    .hidden {display:none;}
    img { width:200px; }
    &#13;
    <table>
      <tr>
        <td>
          <img id="placeholder" class="hidden">
        </td>
      </tr>
    </table>
    &#13;
    &#13;
    &#13;

    1. 在您需要的页面中的位置插入动态创建的图像。
    2. &#13;
      &#13;
      var userID = prompt("Enter the ID of the user you want to search for. \nFor this test, enter 169");
      
      // Get a reference to the placeholder:
      var placeholder = document.getElementById("placeholder");
      
      // Dynamically create and configure the new image
      var img = document.createElement("img");
      
      img.classList.add("hidden");
      
      // Set up a load event handler that will unhide the image once its loaded
      img.addEventListener("load", function(){
        this.classList.remove("hidden");
      });
      
      // Inject the image into the document
      placeholder.appendChild(img);
      
      // Update the source of that image (which will cause the load event to trigger)
      img.src = "http://i2.cdn.cnn.com/cnnnext/dam/assets/150409124320-20-cnnphotos-hubble-restricted-super-" + userID + ".jpg";
      &#13;
      .hidden {display:none;}
      img { width:200px; }
      &#13;
      <table>
        <tr>
          <td id="placeholder"></td>
        </tr>
      </table>
      &#13;
      &#13;
      &#13;

      使用这些方法之一,您需要在页面加载后运行脚本,因此只需将<script>元素放在body</body>)结尾之前。这比将脚本注入到您真正想要图像的页面中间更好。它使脚本与HTML分开。