繁体   English   中英

jQuery命令未执行,看不到我在做什么

[英]Jquery command not executing, can't see what I'm doing wrong

我试图使用Jquery通过API访问随机报价。 我对此很陌生,因此我确定有一个我看不到的简单解决方案。 基本上这是我的HTML代码:

<div class="col-md-6">
  <button id="quoteClick" type="button" class="btn btn-success btn-lg quoteButton text-center btn-block">Get Quote</button>
</div>


  <div class="row">
    <div class="col-md-2">
    </div>
    <div class="col-md-8 show boxed text-center">
      Text
    </div>
    <div class="col-md-2">
    </div>
  </div>

我的JS是这样的:

$(document).ready(function() {
  $("#quoteClick").on("click", function() {
    $.getJSON("https://crossorigin.me/http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en", function(json) {
      var html = "";

        json.forEach(function(x) {

          html += "<div class = 'quote'>";


          html += "<h3 '" + x.quoteText + "' "+ "'>";

          html += "</div>";

        });

        $(".show").html(html);

      });
    });
  });

当我使用console.log(json)时,我可以打印要查询的对象,但是当我实际尝试提取报价并将其打印在我的网页上时,什么也没发生。 我正在使用Codepen。

您不应该遍历从API获得的对象。 如果看一个API调用,我得到的结果如下:

{
  "quoteText": "To be thoughtful and kind only takes a few seconds compared to the timeless hurt caused by one rude gesture.",
  "quoteAuthor": "Byron Pulsifer",
  "senderName": "",
  "senderLink": "",
  "quoteLink": "http:\/\/forismatic.com\/en\/4255d6ba93\/"
}

您只需要删除forEach调用,您的代码即可使用。

另外(gavgrif在回答中首先指出了这一点),您的HTML格式不正确-您应该在h3中包含该文本。

这应该更好:

$(document).ready(function() {
    $("#quoteClick").click(function() {
        $.getJSON("https://crossorigin.me/http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en", function(json) {
            var html = "";
            html += "<div class = 'quote'>";
            html += "<h3>" + json.quoteText + "</h3>";
            html += "</div>";
            $(".show").html(html);
        });
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM