首页 > 解决方案 > 如何使用数组更改 html 元素属性

问题描述

您好我正在尝试让这个脚本工作,但它只是不能正常工作 getquote 函数从定义的 arr 获取报价和随机颜色,然后根据它获得的数据更新页面。调用 getquote 后,没有任何输出按预期工作

任何人都可以帮我告诉我故障来自哪里或指出损坏的部分吗?

var colors = [
  '#490A3D',
  '#BD1550',
  '#E97F02',
  '#F8CA00',
  '#8A9B0F',
  '#69D2E7',
  '#FA6900',
  '#16a085',
  '#27ae60',
  '#2c3e50',
  '#f39c12',
  '#e74c3c',
  '#9b59b6',
  '#FB6964',
  '#342224',
  '#472E32',
  '#77B1A9',
  '#73A857'
];

var quotes = [
  ["You only live once, but if you do it right, once is enough.", "Mae West"]
]

var currentQuote = "";
var currentAuthor = "";
var randomquote = "";
var randomcolor = "";

function getQuote() {
  randomquote = Math.floor(Math.random() * quotes.length);
  randomcolor = Math.floor(Math.random() * colors.length);
  currentQuote = quotes[randomquote][0];
  currentAuthor = quotes[randomquote][1];

  $(document).ready(function() {
    $('html body').animate({
      backgroundColor: colors[randomcolor],
      color: colors[randomcolor]
    }, 500);
    $('#newquote, .social-icons .fa-twitter').animate({
      backgroundColor: colors[randomcolor]
    }, 500);
    $('blockquote footer').animate({
      color: colors[randomcolor]
    }, 500);
    $('blockquote').animate({
      borderLeftColor: colors[randomcolor]
    }, 500);
    $('#quotetext').animate({
      opacity: 0
    }, 500, function() {
      $(this).animate({
        opacity: 1
      }, 500);
      $(this).text(currentQuote);
    });
    $('#quotesource').animate({
      opacity: 0
    }, 500, function() {
      $(this).animate({
        opacity: 1
      }, 500);
      $(this).text(currentAuthor);
    });
  });
}



getQuote();

$(document).ready(function() {
  $('#newquote').on('click', getQuote());

});
body {background:#16a085;}
.btn-primary {
    width: 100px;
    height: 40px;
    background:#490A3D;
    }
<body>
<h2 id="quotetext"></h2>
<footer id="quotesource"></footer>
<button class="btn btn-primary" id="newquote">New Quote</button>
</body>

标签: javascript

解决方案


$(document).ready(function() {
  $('#newquote').on('click', getQuote);

});

您需要将回调作为变量传递。在您的示例中,它被调用并且函数的结果(什么都没有)被传递给事件侦听器。

Codepen 上的工作代码


推荐阅读