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));
});
});
});
答案 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>