簡體   English   中英

無法在jQuery函數中分配變量

[英]Can't assign variable in jQuery function

因此,我有一個按鈕,該按鈕應該通過運行函數來使變量“ quote”。 然后,我們使用jQuery在頁面上顯示報價,但是每當我嘗試分配變量時,jQuery函數就在那里停了下來,沒有任何反應。 我不知道發生了什么事。 這是按鈕代碼和javascript。非常感謝!

<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]);

});

您有一個變量和一個名為相同的函數。 您應該給函數命名不同的名稱,以免它們沖突(即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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM