简体   繁体   English

页面加载随机div

[英]random div on page load

I am trying to randomize the hero content of a home page. 我正在尝试随机化主页的英雄内容。 I have this simple code, but it affects all the divs on the page, and I only want it to affect a few. 我有这个简单的代码,但是它会影响页面上的所有div,我只希望它影响几个。

var elems = $("div");
if (elems.length) {
var keep = Math.floor(Math.random() * elems.length);
for (var i = 0; i < elems.length; ++i) {
if (i !== keep) {
  $(elems[i]).hide();
}
}
}

Here is my html: 这是我的html:

<div id="hero1">One</div>

<div id="hero2">Two</div>

<div id="hero3">Three</div>

<div id="constant">This content does not rotate.</div>

There is another caveat to this, I need it to work within a crappy CMS that strips out my class tags. 还有一个警告,我需要它在一个糟糕的CMS中工作,以剥离我的班级标签。 So it has to be a solution that identifies the divs based on id. 因此,它必须是一种基于id标识div的解决方案。

How about 怎么样

var elems = $('div').not('#constant')

?

The not function removes matching elements from the set it's called on. not函数从调用的集合中删除匹配的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM