【问题标题】:Creating button that displays different content when clicked创建单击时显示不同内容的按钮
【发布时间】:2015-09-27 08:30:18
【问题描述】:

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

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

【问题讨论】:

    标签: jquery button random eventhandler


    【解决方案1】:

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

    var new_random, old_random;
    function random_num(){
        return Math.floor((Math.random() * quotes.length));
    }    
    
    $(document).ready(function() {
       $(".quote-button").click(function() {
            new_random = random_num(); //Generate a random number
            while(new_random == old_random){ // Check if previous and new are equal
                new_random = random_num();//if equal generate another
            }
            $('#quote-box p').html(quotes[new_random].q);
            $('#quote-box a').attr('href', quotes[new_random].l);
            $('quote-box a').html(quotes[new_random].a);
            old_random = new_random;
        });
    });
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-14
        • 1970-01-01
        • 1970-01-01
        • 2017-08-28
        • 1970-01-01
        相关资源
        最近更新 更多