单击时创建显示不同内容的按钮

时间:2015-07-09 06:11:14

标签: jquery button random eventhandler

我是Jquery和Web开发的新手,我正在尝试构建一个随机引用生成器。

网络应用程序包含一个按钮,单击该按钮会显示新报价。它是一个静态站点,全部用html / css / jquery完成。

我的问题是,当单击按钮时,它会显示第一个引号,但再次单击时它不会更改。我想按钮每次点击都会显示一个新的报价。

对于精通Jquery的人来说,我确信这是一个简单的解决方法:

  $(document).ready(function() {
  $(".quote-button").click(function() {
    $('#quote-box p').html(quotes[i].q);
    $('#quote-box a').attr('href', quotes[i].l);
    $('quote-box a').html(quotes[i].a);
  });
});

var quotes = [{
    q: 'The Great Man … is colder, harder, less hesitating, and without respect and  without the fear of “opinion”; he lacks the virtues that accompany respect and “respectability”, and altogether everything that is the “virtue of the herd”. If he cannot lead, he goes alone. … He knows he is incommunicable: he finds it tasteless to be familiar. … When not speaking to himself, he wears a mask. There is a solitude within him that is inaccessible to praise or blame. - Friedrich Nietzche, The Will to Power'
  }, {
    q: 'Power is given only to those who dare to lower themselves and pick it up. Only one thing matters, one thing; to be able to dare! Fyodor Dostoevsky'
  }, {
    p: 'The more sand has escaped from the hourglass of our life, the clearer we should see through it. Niccolo Machiavelli'
  }

];

var i = Math.floor((Math.random() * quotes.length));

2 个答案:

答案 0 :(得分:0)

问题在于,在运行时,变量i被声明为特定的随机数,因此再次单击它会显示完全相同的引号(因为i不会更改)。

var i = Math.floor((Math.random() * quotes.length));放在.click()事件处理程序中。

答案 1 :(得分:0)

问题是您生成的随机数可能等于先前生成的随机数,因此不会反映出来。因此,您可以检查先前的随机是否不等于新的随机数,否则生成一个新的随机数。您可以使用以下代码:

nr
com_disagg
nr
inside head
head printed
com_disagg
inside head
head printed
nr
inside head
head printed
com_disagg
inside head
head printed