无法在jQuery函数中赋值变量

时间:2016-12-27 21:08:52

标签: javascript jquery

所以我有一个按钮,它应该是一个变量"引用"从运行功能。然后我们jQuery在页面上显示引号,但每当我尝试分配变量时,jQuery函数就会停在那里并且没有任何反应。我不知道怎么会陷入困境。这里是按钮代码和javascript.Thanks很多!

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

});

1 个答案:

答案 0 :(得分:2)

您有一个变量和一个名为相同的函数。你应该将你的功能命名为不同的,这样它们就不会碰撞(即getQuote()):

&#13;
&#13;
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]);

});
&#13;
<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>
&#13;
&#13;
&#13;

相关问题