如何使用新内容替换图像容器中的内容?

时间:2017-03-09 09:53:10

标签: javascript html

我正在使用Giphy的API来学习如何制作随机GIF生成器。下面的代码适用于生成一个GIF并将其放入<!doctype html> <meta charset="utf-8"> <title>Bootstrap Nodes</title> <link rel="stylesheet" href="demo.css"> <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> <script src="http://cpettitt.github.io/project/dagre-d3/latest/dagre-d3.js"></script> <script src="https://code.jquery.com/jquery-2.0.2.min.js"></script> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <div id='panel' class='panel panel-primary'> <div class='panel-heading fixed-panel-head'> <h3 class='panel-title'> <h3 class='panel-title'> <span class='glyphicon glyphicon-star'></span> Sample</h3> </h3> </div> <div class='panel-body fixed-panel-foot'> <div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> Dropdown <span class="caret"></span> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li role="separator" class="divider"></li> <li><a href="#">Separated link</a></li> </ul> </div> </div> </div> <style id="css"> .fixed-panel-head { min-height: 40px; max-height: 40px; } .fixed-panel-foot { min-height: 60px; max-height: 60px; } .node g div { width: auto; height: 100px; color: #000; } .edgePath path { stroke: #333; stroke-width: 1.5px; } </style> <svg id="svg-canvas" width=100% height=600></svg> <script id="js"> // Create the input graph var g = new dagreD3.graphlib.Graph() .setGraph({}) .setDefaultEdgeLabel(function() { return {}; }); var element = document.getElementById("panel"); var elementHtml = element.outerHTML; g.setNode((1), { labelType: "html", label: elementHtml, rx: 5, ry: 5, padding: 0 }); g.setNode((2), { labelType: "html", label: elementHtml, rx: 5, ry: 5, padding: 0 }); g.setEdge(1, 2); var render = new dagreD3.render(); // Set up an SVG group so that we can translate the final graph. var svg = d3.select("svg"), svgGroup = svg.append("g"); // Run the renderer. This is what draws the final graph. render(d3.select("svg g"), g); // Center the graph var xCenterOffset = (svg.attr("width") - g.graph().width) / 2; svgGroup.attr("transform", "translate(" + xCenterOffset + ", 20)"); svg.attr("height", g.graph().height + 40); </script>,但我想知道我可以添加什么来在imageContainer按钮imageContainer时显示新的GIF被点击了吗?如现在看来,如果单击按钮,则对更多GIF的请求是成功的,但由于其中已存在GIF,因此它们不会发布到图像容器中。

这是我的JavaScript:

randomDog

这是我的HTML:

document.addEventListener('DOMContentLoaded', function () {

request = new XMLHttpRequest;
request.open('GET', 'http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=cute+dog', true);

document.getElementById("randomDog").onclick = function () {
    if (request.status >= 200 && request.status < 400){
        data = JSON.parse(request.responseText).data.image_url;
        console.log(data);
        document.getElementById("imageContainer").innerHTML = '<center><img src = "'+data+'"  title="GIF via Giphy"></center>';
    } else {
        console.log('reached giphy, but API returned an error');
     }
};

request.onerror = function() {
    console.log('connection error');
};

request.send();
});

提前致谢!

2 个答案:

答案 0 :(得分:0)

只需移动行初始化并在XMLHttpRequest处理程序内发送click,并将成功函数包含在onreadystatechange事件处理程序中。

(请注意,当我在片段中使用时,您正在使用的API密钥会为我返回错误;不确定我将如何解决这个问题,但也许它会在您的最后工作。)

document.addEventListener('DOMContentLoaded', function() {

  document.getElementById("randomDog").onclick = function() {
    request = new XMLHttpRequest;
    request.open('GET', 'http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=cute+dog', true);
    request.onreadystatechange = function() {
      if (request.readyState === 4) {
        if (request.status >= 200 && request.status < 400) {
          data = JSON.parse(request.responseText).data.image_url;
          console.log(data);
          document.getElementById("imageContainer").innerHTML = '<center><img src = "' + data + '"  title="GIF via Giphy"></center>';
        } else {
          console.log('reached giphy, but API returned an error');
        }
      }
    }
    request.onerror = function() {
      console.log('connection error');
    };

    request.send();
  };

});
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" type="text/css" href="dogstyle.css">
  <meta charset="UTF-8">

  <title>Sadness be gone!</title>
</head>

<body>

  <div id="headers">
    <h1> Having a bad day?</h1>
    <h1> Not anymore! </h1>
  </div>

  <h3 id="subheader">Happiness and fluffyness is just a click away</h3>

  <div id="imageContainer"></div>

  <button id="randomDog" class="button">Click away!</button>

  <script src="js/experiment.js"></script>

</body>

答案 1 :(得分:0)

试试这个

....    
document.getElementById("randomDog").onclick = function () {
        if (request.status >= 200 && request.status < 400){
            data = JSON.parse(request.responseText).data.image_url;
            console.log(data);
            // Clear the existing image first
            document.getElementById("imageContainer").removeChild(document.getElementsByClassName("mygif")[0]);
            // Now set the new image in image container
            document.getElementById("imageContainer").innerHTML = '<center><img class="mygif" src = "'+data+'"  title="GIF via Giphy"></center>';
        } else {
            console.log('reached giphy, but API returned an error');
         }
    };
....