使用JS和foreach循环/追加覆盖div

时间:2017-08-24 14:30:54

标签: javascript html json

我想用JS覆盖一个div,但问题是我使用append所以脚本一直在div的末尾写数据,我不知道如何解决这个问题,我试过window.location.reload(true),但显然数据丢失了。 有人能指出我正确的方向,实际上我迷失了。我的目标是刷新/删除或更新div内容,最好是重新加载页面。这是一个可运行的代码,因此您可以看到问题所在。谢谢你的帮助。



$("#getnews").on("click", function() {
  setTimeout(function() {

    var path = "https://api.iextrading.com/1.0/stock/"
    var stock = document.getElementById('userstock').value
    var end = "/news"

    var url = path + stock + end

        $.getJSON(url, function(data) {
            data.forEach(function (article) {
              $('#data').append(
                  $('<h4>').text(article.headline),
                  $('<div>').text(article.summary),
                  $('<hr>').text(" "),
                );


            });
        }); 
},200);

});
&#13;
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">



<div class="container">
<p>Search for a stock (E.g: msft, aapl or tsla)</p>
<p><input type="text" id="userstock"></p>
<p><a class="btn btn-dark btn-large text-white" id="getnews">Browse</a></p>
<row id="data"></row>
</div>

<script src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

$("#getnews").on("click", function() {
  setTimeout(function() {

    var path = "https://api.iextrading.com/1.0/stock/"
    var stock = document.getElementById('userstock').value
    var end = "/news"

    var url = path + stock + end

        $.getJSON(url, function(data) {
            var html = $("<div></div>");

            data.forEach(function (article) {
              html.append($('<h4>').text(article.headline));
              html.append($('<div>').text(article.summary));
              html.append($('<hr>').text(" "));                
            });

            $('#data').html(html);
        }); 
},200);

});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">



<div class="container">
<p>Search for a stock (E.g: msft, aapl or tsla)</p>
<p><input type="text" id="userstock"></p>
<p><a class="btn btn-dark btn-large text-white" id="getnews">Browse</a></p>
<row id="data"></row>
</div>

<script src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>

答案 1 :(得分:0)

您无法设置容器的HTML:

var html = $("<div></div>");
html.append($('<h4>').text(article.headline));
html.append($('<div>').text(article.summary));
html.append($('<hr>').text(" "));

$('#data').html(html);