javascript - 我想随机显示 div - 我该怎么做?

标签 javascript html

<分区>

我按照教程创建了一个随机报价生成器(使用报价数组),效果很好。

然后我尝试创建相同的随机生成器,而不是显示引号数组中的内部 html,我想让它显示 div,我在其中放置了具有不同内容的 iframe。

这不起作用,并且在控制台中它一直说没有定义 onclick 按钮。

谁能告诉我我是如何开始这样做的?我对 Javascript 完全陌生,主要是从其他地方提取一些代码来尝试看看它是如何工作的。

基本上,我想要一个按钮,单击该按钮会显示一个随机 div。我还希望按钮文本在被单击一次后更改 - 所以如果有人可以帮助我如何做到这一点,那就太好了。

谢谢。

最佳答案

对于您的方法,您需要遍历元素并将样式 display: block(可见)设置为随机元素,同时使用样式 display: none 隐藏其他元素。

这是一个完整的例子:

var w = document.getElementById('wrapper');
var button = document.getElementById('randomize');
var quotes = w.children; // inner elements, your quotes divs

// a function to hide all divs
var hideDivs = function(divs) {
  for (var div of divs) {
    div.style.display = 'none';
  }
}

hideDivs(quotes); // hide all initially

// on click
button.addEventListener('click', function(event) {
  var rnd = Math.floor(Math.random() * quotes.length); // get random index
  hideDivs(quotes); // hide all quotes
  quotes[rnd].style.display = 'block'; // show random quote
  event.target.textContent = 'Click one more time!'; // set button text. event.target is the button you've clicked
})
<div id="wrapper">
  <div class="quote">Chuck Norris counted to infinity... Twice.</div>
  <div class="quote">Chuck Norris has already been to Mars; that's why there are no signs of life there.</div>
  <div class="quote">Guns don't kill people. Chuck Norris kills People.</div>
  <div class="quote">There is no theory of evolution. Just a list of animals Chuck Norris allows to live.</div>
  <div class="quote">Chuck Norris uses pepper spray to spice up his steaks.</div>
</div>
<button id='randomize'>Randomize</button>

关于javascript - 我想随机显示 div - 我该怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44216117/

相关文章:

javascript - 让 div 填满一个包含的 div?

javascript - 柯里化(Currying)函数中第一个函数的命名约定

javascript - CSS 选择器排除任何级别的任何 parent 都有类(class)的所有 child

javascript - 如果复选框被选中则禁用选择

html - 你能提出一种更优雅的方法来将 'tokenize' c# 代码用于 html 格式化吗?

javascript - 为什么无法识别在 moment.js 中使用字符串参数指定的时区?

javascript - 将函数应用于填充数字的对象

javascript - 使用 Vue 添加/删除动态 DOM 元素

css - img {最大高度 :%} fails in chrome

javascript - ReactJS - .JS 与 .JSX