随机引号脚本

时间:2015-02-05 21:14:12

标签: javascript jquery html arrays

尝试在每次轮换时显示随机引用。我已经让它为第一个实例工作,但随后列表恢复到正常顺序。这就是我到目前为止所拥有的:

$(function (){
    var items = (Math.floor(Math.random() * ($('#quotes li').length)));
    $('#quotes li').hide().eq(items).show();

function next(){
    $('#quotes li:visible').delay(6000).fadeOut('slow',function(){
        $(this).appendTo('#quotes ul');
        $('#quotes li:first').fadeIn('slow',next);
});
}
next();
});

干杯

3 个答案:

答案 0 :(得分:1)

您当前的算法(在第一个显示的项目之外没有随机化)如下:

  1. 选择随机<li>标记。隐藏所有其他人并展示这一个。
  2. 延迟之后,淡出随机的一个。
  3. 将其移至列表末尾。
  4. 显示列表中的第一个。
  5. 因此,您将首先选择一个随机的,但从那时起,您将按顺序进行。有许多方法可以将算法更改为更随机,但这取决于您想要的行为(您尚未指定)。

    例如,您可以每次都选择一个随机元素,但这可能会在显示其他元素之前重复元素,而不是尚未显示的元素。

    或者,您可以将<li>标签随机排序,然后以新的随机顺序一个接一个地显示它们。当你到达列表时,做另一个随机的随机播放等...

    这是执行随机随机播放的代码版本。它将所有元素按随机顺序排列,然后逐个显示它们,直到它到达最后一个元素。在显示最后一个之后,它再次以随机顺序重新排列元素,然后再次开始逐个显示它们,重复一遍又一遍。这保证了随机顺序,并且它保证在一次运行中,您不重复元素,因此所有元素都显示相同的次数。有可能(由于随机机会)相同的元素可能连续两次显示,但这只有在一次传递中显示为最后一个元素然后被随机机会选为第一个元素时才会发生。下一次运行。

    以下是代码:

    // efficient way to randomize an array of values
    function fisherYatesShuffle(array ){
        var count = array.length,
          randomnumber,
          temp;
        while( count ){
            randomnumber = Math.random() * count-- | 0;
            temp = array[count];
            array[count] = array[randomnumber];
            array[randomnumber] = temp;
        }
    }
    
    $(function() {
        var index = 0;
        var quotesArray = $('#quotes li').get();
        var numItems = quotesArray.length;
    
        // randomize the elements
        function randomize() {
            fisherYatesShuffle(quotesArray);
        }
    
        // make sure the index is not past the end of the array
        // if so, randomize the elements again and reset the index
        function checkIndex() {
            if (index >= numItems) {
                randomize();
                index = 0;
            }
        }
    
        // process the next item with 6 second delay, then fadeOut, then fadeIn of next element
        function next() {
            $(quotesArray[index]).delay(6000).fadeOut('slow', function() {
                ++index;
                checkIndex();
                $(quotesArray[index]).fadeIn('slow', next);
            });
    
        }
        // randomize the items initially and show the first one after randomization
        randomize();
        $('#quotes li').hide();
        $(quotesArray[0]).show();
        next();
    });
    

    工作演示(带实际引号):http://jsfiddle.net/jfriend00/gf5y46cp/

    仅供参考,这是一篇关于Javascript的Fisher-Yates shuffle的文章:http://bost.ocks.org/mike/shuffle/

答案 1 :(得分:1)

这是另一种解决问题的方法,我认为这个方法更清晰:

// An array of possible quotes
var quotes = [
    'Genius is one percent inspiration, ninety-nine percent perspiration. (Thomas Edison)', 
    'The real problem is not whether machines think but whether men do. (B.F. Skinner)',
    'There are only two hard things in Computer Science: cache invalidation and naming things. (Phil Karlton)',
    'If today were the last day of your life, would you want to do what you are about to do today? (Steve Jobs)'];
var currentQuote = 0;

function nextQuote(showImmediately) {
    // We can use a promise to make sure that we don't switch the
    // quote out until the text is hidden
    var hidden = $.Deferred();

    if (!showImmediately)
        $('#quotes').fadeOut('slow', function() { hidden.resolve(); });
    else
        hidden.resolve();

    // Once the promise is resolved, go ahead and modify the DOM
    hidden.promise().done(function() {

        // Get a quote that's not the current one
        // (we may need to try a few times if it's a small array
        var randomIndex = currentQuote;
        while (randomIndex == currentQuote) {
            randomIndex = (Math.floor(Math.random() * quotes.length));
        }

        // Now switch it out and fade back in        
        $('#quotes').html(quotes[randomIndex]);
        $('#quotes').fadeIn('slow');
        currentQuote = randomIndex;
    });
}

nextQuote(true);
setInterval(function() { nextQuote(false); }, 6000);

工作小提琴:here

答案 2 :(得分:0)

尝试以下脚本,它会显示引号数组的随机引用。

&#13;
&#13;
(function() {
  var arrayQ = [{
    quote: "The material world is a dangerous place to be in. It's dangerous because there is a temptation of illusory energy; there is danger at every step.",
    source: "HH GOPAL KRISHNA GOSWAMI",
    citation: "ISKCON DESIRE TREE",
    year: 2016
  }, {
    quote: "If you carry out the order of your spiritual master then the Lord will be so pleased that He will come to see you.",
    source: "HH GOPAL KRISHNA GOSWAMI",
    citation: "ISKCON DESIRE TREE",
    year: 2013
  }, {
    quote: "Our vaccination is chanting the names of Krishna, Hearing the Bhagavad-gita and Srimad Bhagavatam, and thinking of Krishna all the time.",
    source: "HH GOPAL KRISHNA GOSWAMI",
    citation: "ISKCON DESIRE TREE",
    year: 2003
  }, {
    quote: "Vairagya means that when the opportunity for sense gratification is there, I voluntarily abstain from it.",
    source: "HH GOPAL KRISHNA GOSWAMI",
    citation: "ISKCON DESIRE TREE",
    year: 2006
  }, {
    quote: "Our quota is not sixteen rounds, but attentive sixteen rounds.",
    source: "HH GOPAL KRISHNA GOSWAMI",
    citation: "ISKCON DESIRE TREE",
    year: 2009
  }, {
    quote: "Guru is pleased when he sees that the disciple is showing the symptoms of Shudh Bhakti.",
    source: "HH GOPAL KRISHNA GOSWAMI",
    citation: "ISKCON DESIRE TREE",
    year: 2010
  }, {
    quote: "Devotional service is so simple, but devotees because of their material inclinations make it complicated.",
    source: "HH GOPAL KRISHNA GOSWAMI",
    citation: "ISKCON DESIRE TREE",
    year: 2011
  }, {
    quote: "Whatever we give to Krishna that will be remembered eternally, that will be appreciated eternally.",
    source: "HH GOPAL KRISHNA GOSWAMI"
  }, ];

  var randomQuotes = function() {
    var getRandomInt = function(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
      },
      index = getRandomInt(0, arrayQ.length),
      quote = arrayQ[index],
      quoteElm = document.getElementById('quote');
    if (quote) {
      quoteElm.innerHTML = quote.quote;
      arrayQ.splice(index, 1); // remove quote from array
    }
  };
  setInterval(function() {
    randomQuotes()
  }, 1500);
})();
&#13;
#quote {
  border-radius: 25px;
  background: yellow;
  padding: 20px;
  width: 200px;
  min-height: 20px;
}
&#13;
<div id="quote"></div>
&#13;
&#13;
&#13;