如何使用if语句添加图像

时间:2015-09-24 21:15:12

标签: javascript if-statement

当使用if语句将某个短语输入到输入中时,是否可以显示图像?这是我的代码

<script type="text/javascript">

    document.getElementById("button").onclick=function() {

        var ask=document.getElementById("ask").value.toLowerCase(); ;
        if (ask =="how tall are the pyramids") {

            document.getElementById("spanId").innerHTML = "146.5 meters";

        } else if (ask== "how tall is the gateway arch") {

            document.getElementById("spanId").innerHTML = "630 feet";

        }

3 个答案:

答案 0 :(得分:1)

您需要做的就是设置图片的路径 - 这会将图片从网络服务器上加载:

<script type="text/javascript">

document.getElementById("button").onclick=function() {

    var imageSrc = "";

    var ask=document.getElementById("ask").value.toLowerCase(); ;
    if (ask =="how tall are the pyramids") {
        document.getElementById("spanId").innerHTML = "146.5 meters";
        imageSrc = "pyramids.jpg";
    } else if (ask== "how tall is the gateway arch") {
        document.getElementById("spanId").innerHTML = "630 feet";
        imageSrc = "arch.jpg";
    }

    // update the image
    document.getElementById("image_placeholder").src = imageSrc;

你也可以预先加载&#34;所有图像,以便UI感觉更快捷。为此,您可以在循环中创建Image个对象,并将.src设置为图像&#39;路径。加载后,图像翻转将立即生效。

答案 1 :(得分:1)

您可以尝试 -

document.getElementById("spanId").innerHTML = "<img src='path/arch.jpg'>";

document.getElementById("spanId").innerHTML = "<p>630 feet</p><img src='path/gatewayarch.jpg'>";

答案 2 :(得分:0)

是的,有一些方法可以达到你想要的效果,例如:

if (ask =="how tall are the pyramids") {
  document.getElementById("spanId").innerHTML = "146.5 meters <img src='yourimg.png'>";

或者:

var img = document.createElement('img');

if (ask =="how tall are the pyramids") {
  var span = document.getElementById("spanId");
  span.innerHTML = "146.5 meters";
  img.src = 'yourimg.png';
  span.appendChild(img);

或者,如果您的网络服务器中没有实际的图像,则可以执行以下操作:

if (ask =="how tall are the pyramids") {
  var base64 = 'YOUR_IMAGE_BASE64_STRING';
  document.getElementById("spanId").innerHTML = '146.5 meters <img src="data:image/jpg;base64,' + base64 + '" />';

您可以使用this converter将您拥有的任何图片转换为base64字符串。