2 回答
TA贡献1788条经验 获得超4个赞
您在附加处理程序时调用这些函数,因此在没有附加适当的处理程序的情况下调用它们,并且仅调用一次。
您只需要函数定义:
$('#new-quote').click(renderQuoteToPage);
...
$(document).ready(renderQuoteOnPageLoad);
编辑:您还需要randomNumber在每次getQuote()通话时进行设置
// https://type.fit/api/quotes //
// api link for quotes //
const button = document.getElementById('new-quote');
const baseUrl = 'https://type.fit/api/quotes';
let randomNumber
function getQuote() {
randomNumber = Math.floor(Math.random() * 100);
fetch(baseUrl)
.then(response => response.json())
.then(quote => $('#text-output').text(quote[randomNumber].text))
};
function getAuthor() {
fetch(baseUrl)
.then(response => response.json())
.then(quote => $('#author').text(quote[randomNumber].author))
};
function renderQuoteToPage() {
getQuote();
getAuthor();
}
$('#new-quote').click(renderQuoteToPage);
$(document).ready(renderQuoteToPage);
body {
width: 100%;
height: auto;
}
#outer-wrapper {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="outer-wrapper" class="container-fluid">
<div id="quote-box" class="card w-50">
<div class="card-body">
<div class="row">
<div class="col">
<div id="text">
<p id="text-output"></p>
</div>
</div>
</div>
<div class="row">
<div class="col">
<a href="#" id="tweet-quote">Tweet</a>
</div>
<div class="col">
<div id="author">Author</div>
</div>
</div>
<div class="row">
<div class="col">
<button id="new-quote">New quote</button>
</div>
</div>
</div>
</div>
</div>
TA贡献1891条经验 获得超3个赞
您的脚本几乎没有变化,并且已经完成。
<script>
const button = document.getElementById('new-quote');
const baseUrl = 'https://type.fit/api/quotes';
let randomNumber;
function getQuote() {
fetch(baseUrl)
.then(response => response.json())
.then(quote => $('#text-output').text(quote[randomNumber].text))
};
function getAuthor() {
fetch(baseUrl)
.then(response => response.json())
.then(quote => $('#author').text(quote[randomNumber].author))
};
function renderQuoteOnPageLoad() {
randomNumber = Math.floor(Math.random() * 100);
getQuote();
getAuthor();
}
$(document).ready(function(){
renderQuoteOnPageLoad();
});
$(document).on("click","#new-quote",function(){
renderQuoteOnPageLoad()
})
</script>
- 2 回答
- 0 关注
- 130 浏览
添加回答
举报