0
点赞
收藏
分享

微信扫一扫

随机点名案例

南陵王梁枫 2022-04-29 阅读 103

随机点名

  • 通过将随机整数作为姓名数组的索引值,然后依次取出。取出后将其从数组中删除。
  • 姓名数据:
    var arr = [ "刘志远", "万策", "李博文", "曹建莹", "张佳祺", "赵瑞瑞", "陈全虎", "胡金朋", "耿建丽", "王如雪", "王振涛", "刘放", "张亚迪", "朱翔煜", "王奥", "薛澳飞", "刘志玮", "胡高洋", "周畅", "赵英杰", "徐亚美", "郑勇超", "闻吉祥", "王阿雨", "陈德帅", "申林益", "赵艳哲", " 肖梦飞", "鲍尔欣", "代星澳", "汪青", "谢森成", "雷吕能", "丁康宁", "杨泽文", "王永杰", "侯振强", "马建成", "朱保森", "王皓圆", "孙秀婷", "靳丹丹", "李聪", "纪妍", "苏文璇", ];
/* 
      1.点击开始按钮随机抽取数组中的一个数据,放到页面中。
      2.点击结束按钮删除数组当前抽取的一个数据
      3.当抽取到最后一个数据时,禁用两个按钮。
      */

HTML代码

<body>
<div class="content">刘志远</div>
  <button id="start">start</button>
  <button id="end">end</button>
  <script>
  //获取元素
    var content = document.querySelector(".content");
    var start = document.querySelector("#start");
    var end = document.querySelector("#end");
    let timer = 0;
    let random = 0;

    function getRandom(min, max) {
      return Math.floor(Math.random() * (max - min + 1) + min);
    }
    //开始按钮注册事件
    var flag = null;
    start.addEventListener("click", function () {
      //随机抽取数据       快速不断的抽取数据\
      flag = true;
      start.disabled = true;
      timer = setInterval(function () {
        random = getRandom(0, arr.length - 1);
        content.innerHTML = arr[random];
      }, 1000);
      // 禁用按钮
      if (arr.length === 1) {
        start.disabled = end.disabled = true;
      }
    });
    //结束按钮注册事件
    end.addEventListener("click", function () {
      if (flag) {
        flag = false;
        //停止定时器
        clearInterval(timer);
        //删除数组元素
        arr.splice(random, 1);
        console.log(arr);
        start.disabled = false;
      }
    });
  </script>
</body>
举报

相关推荐

0 条评论