2016-12-27 44 views
0

所以我有一個按鈕,應該使運行函數的變量「quote」。然後我們用jQuery在頁面上顯示報價,但每當我嘗試分配變量時,jQuery函數就會停在那裏,並且什麼也沒有發生。我不知道什麼會被抓住。這裏是按鈕代碼和javascript.Thanks很多!無法在jQuery函數中分配變量

<button class="btn btn-primary" id="quoteBtn">new quote</button> 


var quote = quote(); 

function quote() { 
    var num = randomRange(1, 3); 
    switch (num) { 
    case 1: 
     return ["hat.", "- hatboy"]; 
    case 2: 
     return ["shoes.", "- shoeboy"]; 
    case 3: 
     return ["belt.", "- beltboy"]; 
    } 
} 
function randomRange(min, max) { 
    return Math.floor(Math.random() * (max - min + 1)) + min; 
} 

$(document).ready(function() { 
    $("#quoteBtn").on("click", function() { 
    var quote = quote(); 
    $("h2").html("<i class=\"fa fa-quote-left fa-lg\"></i>" + " " + quote[0]); 
    $("#author").html(quote[1]); 
    }); 
    $("h2").html("<i class=\"fa fa-quote-left fa-lg\"></i>" + " " + quote[0]); 
    $("#author").html(quote[1]); 

}); 
+0

怎麼樣的鏈接codepen?或者至少在堆棧溢出上創建... –

+4

也許你的變量'var quote'應該有一個不同的名字。我認爲它可能會覆蓋你的'函數報價'。 – putvande

回答

2

你有一個變量和一個名字相同的函數。您應該爲您的功能不同的東西,使他們不衝突(即getQuote()):

var quote = getQuote(); 
 

 
function getQuote() { 
 
    var num = randomRange(1, 3); 
 
    switch (num) { 
 
    case 1: 
 
     return ["hat.", "- hatboy"]; 
 
    case 2: 
 
     return ["shoes.", "- shoeboy"]; 
 
    case 3: 
 
     return ["belt.", "- beltboy"]; 
 
    } 
 
} 
 
function randomRange(min, max) { 
 
    return Math.floor(Math.random() * (max - min + 1)) + min; 
 
} 
 

 
$(document).ready(function() { 
 
    $("#quoteBtn").on("click", function() { 
 
    var quote = getQuote(); 
 
    $("h2").html("<i class=\"fa fa-quote-left fa-lg\"></i>" + " " + quote[0]); 
 
    $("#author").html(quote[1]); 
 
    }); 
 
    $("h2").html("<i class=\"fa fa-quote-left fa-lg\"></i>" + " " + quote[0]); 
 
    $("#author").html(quote[1]); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="quoteBtn">Quote</button> 
 
<h2></h2> 
 
<div id="author"></div>