如何使用Jquery

时间:2016-07-17 05:56:29

标签: javascript jquery json

JSON.stringify()JSON格式显示内容。我希望quote类中的引号和character类中的字符。所以点击按钮i'将显示消息和报价。

//HTML

<div class="container-fluid">
  <div class = "row text-center">
    <h2>GOT Quotes</h2>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12 well quote">
      The message will go here
      <br>
      <div class = "col-xs-12 well character">
        Said By
      </div>
    </div>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12">
      <button id = "getMessage" class = "btn btn-primary">
        Get Message
      </button>
    </div>
  </div>
</div>

//JS

<script>$(document).ready(function () {
    $('#getMessage').click(function () {
        $.getJSON('https://got-quotes.herokuapp.com/quotes', function (json) {
            $('.quote').html(JSON.stringify(json));
        });
    });
});

1 个答案:

答案 0 :(得分:3)

这是你想要的吗?请注意,我已将quote班级移至span内的div,因此您不会覆盖嵌套的character div。我还使用.text()代替.html()。如果您正在处理文本,这是正确的做法。

$(document).ready(function () {
    $('#getMessage').click(function () {
        $.getJSON('https://got-quotes.herokuapp.com/quotes', function (data) {
            $('.quote').text(data.quote);
            $('.character').text(data.character);
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
  <div class = "row text-center">
    <h2>GOT Quotes</h2>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12 well">
      <span class="quote">The message will go here</span>
      <br>
      <div class = "col-xs-12 well character">
        Said By
      </div>
    </div>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12">
      <button id = "getMessage" class = "btn btn-primary">
        Get Message
      </button>
    </div>
  </div>
</div>