jQuery随机blockquote

我花了两个多小时寻找和测试这个问题的各种解决方案,但收效甚微,所以我不得不请求帮助。

我想建立一个引号数组,每个引号都有引用和链接,随机抽取。 我不需要任何更多的东西来改变页面刷新。

但是,我有一些非常好吃的CSS来设计blockquote和引用。

下面是一些示例HTML,用于说明数组中的内容如何适合引用:

A line of oversize watches that can offer many of the attributes of premium luxury watches at an affordable price.

Horozima

此代码的预期位置是Big Cartel产品(模板)页面,其中包含为每个产品自动生成的内容。 因此,如果没有一些随机化的JS,每个产品页面上都会出现相同的引用。

在DOMReady上执行JavaScript以使用random()函数生成随机数。 如果将此数字乘以一个值,您将得到一个介于0和值之间的随机数(但不包括值本身)。 如果将引号放入JSON数组中,则可以将数组的.length属性用于乘以的值,因为数组中的项数比最后一项的索引大1。 这将生成一个随机数,该数字是数组的索引之一。

在此之后,使用jQuery的text()函数替换段落和引文标签的文本以显示您随机选择的引用。

这是一个例子: http : //jsfiddle.net/sWvGp/

HTML:

 

使用Javascript:

 var myQuotes = [{ quote: "To err is human; to forgive, divine.", cite: "Alexander Pope", url: "http://www.example.com" }, { quote: "Reports of my death have been greatly exaggerated.", cite: "Mark Twain", url: "http://www.example.com" }, { quote: "A line of oversize watches that can offer many of the attributes of premium luxury watches at an affordable price.", cite: "Horozima", url: "http://www.horozima.com/2012/07/terranaut-xl-50mm.html" }]; var randomQuote = Math.floor(Math.random() * myQuotes.length) $('p', '#randomquote').text(myQuotes[randomQuote].quote); $('cite a', '#randomquote').attr('href', myQuotes[randomQuote].url).text(myQuotes[randomQuote].cite); 

根据您的优势,您可以“快速而肮脏”或作为正确的解决方案。

正确的解决方案是让服务器端部分代码从数据库中提取随机行,并将其呈现如上。 由于你的标签与它无关,我将跳过

快速而肮脏的解决方案,即有一个javascript数组的引号和链接,以及一个随机的显示:

 $(document).ready(function() { var questions = [ {q: 'This is question 1', l: 'http://this.is.link1', a: 'Test' }, {q: 'This is question 2', l: 'http://this.is.link2' , a:'Another'} ]; var i = Math.floor((Math.random()*questions.length)); $('blockquote p').html(questions[i].q); $('blockquote a').attr('href', questions[i].l); $('blockquote a').html(questions[i].a); }); 

你可以看到生活在一个jsFiddle 。 它假设只有一个块引用,但它可以很容易地扩展。 您可以在HTML中输出单引号,以便在禁用JS时使其看起来正常。