【发布时间】:2010-03-23 05:25:06
【问题描述】:
如何随机显示总共 10 个 div 中的 3 个?
这是我迄今为止尝试过的:
HTML:
<div id="1">Content 1</div>
<div id="2">Content 2</div>
<div id="3">Content 3</div>
<div id="4">Content 4</div>
<div id="5">Content 5</div>
<div id="6">Content 6</div>
Javascript:
function randomiseDiv()
{
// Define how many divs we have
var divCount = 6;
// Get our random ID (based on the total above)
var randomId = Math.floor(Math.random()*divCount+1);
// Get the div that's been randomly selectted
var chosenDiv= document.getElementById(randomId);
// If the content is available on the page
if (chosenDiv)
{
// Update the display
chosenDiv.style.display = 'block';
}
}
window.onload = randomiseDiv;
我更喜欢 PHP 解决方案,尽管现阶段的任何事情都会有所帮助。
【问题讨论】:
-
你不是已经有了吗...?您发布的代码?...
-
每个div中显示的数据是从哪里来的?这 10 行是你从执行 SQL 查询中得到的吗?
-
没有数据库。就示例而言,唯一的内容是“内容 x”。目前粘贴的代码不起作用,有什么建议吗?
-
javascript 通常不喜欢数字作为 id,使用字符串。 (而且有些客户不喜欢字符串以数字开头。)
-
@kennebec 你建议我叫 div 什么?
标签: php javascript html random