[英]Jquery Click function only changes HTML once
單擊按鈕將更改HTML,但是當我再次單擊按鈕時,它將僅重新加載已更改的HTML。 我希望它再次將HTML更改為其他內容(隨機)。
(我有一個叫做'list'的JSON變量,帶有一串引號)
為什么每次我按下按鈕時都不會跳過最后一個按鈕? 我認為該功能基本上會重復。
Javascript:
var number = Math.floor(Math.random() * list.length);
$(document).ready(function() {
$(".clickMe").on('click', function() {
$("#quoteMsge").html(list[number].quote);
$("#author").html(list[number].by);
});
});
HTML:
<h1> Generate your quote! </h1>
<div class="outer">
<div class="inner">
<h2 id="quoteMsge"><i class="fa fa-quote-left"></i>
Generate a quote!</h2>
<h3 id="author">- Me</h3>
<div class="button">
<button class="btn btn-primary clickMe">Gimme a Quote!</button>
</div>
</div>
</div>
我已經花了幾個小時了,但是我是菜鳥,所以請原諒我。 我使用了setInterval函數,該函數確實起作用,但似乎不正確? 那可行嗎?
在此先感謝您的任何建議。
嘗試這個
$(document).ready(function() {
$(".clickMe").on('click', function() {
var number = Math.floor(Math.random() * list.length);
$("#quoteMsge").html(list[number].quote);
$("#author").html(list[number].by);
});
});
您僅生成一次隨機數,因此,每次單擊都會添加相同的數字。
使用此代碼:
var number = Math.floor(Math.random() * list.length);
$(document).ready(function() {
$(".clickMe").on('click', function() {
number = Math.floor(Math.random() * list.length);
$("#quoteMsge").html(list[number].quote);
$("#author").html(list[number].by);
});
});
這是一個演示它的片段:
var list = [{ 'quote': 'Quote 1', 'by': 'Author 1', }, { 'quote': 'Quote 2', 'by': 'Author 2', }, { 'quote': 'Quote 3', 'by': 'Author 3', }] var number = Math.floor(Math.random() * list.length); $(document).ready(function() { $(".clickMe").on('click', function() { number = Math.floor(Math.random() * list.length); $("#quoteMsge").html(list[number].quote); $("#author").html(list[number].by); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="button" class="clickMe" value="Click Me"> <div>Message: <p id="quoteMsge" style="display:inline-block"></p> </div> <div>Author: <p id="author" style="display:inline-block"></p> </div>
您必須將隨機數的創建放入事件函數中:
$(document).ready(function() {
$(".clickMe").on('click', function() {
var number = Math.floor(Math.random() * list.length);
$("#quoteMsge").html(list[number].quote);
$("#author").html(list[number].by);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.