多个DIV随机显示JSON数据?

新手上路,请多包涵

多个DIV里面包含姓名和电话,我需要点击按钮后,开始不断的一直从JSON读取数据不重复的随机更换里面的nametel请问该怎么做?先谢谢啦!~

<div class="box">
    <div class="item">
        <div class="name">张三</div>
        <div class="tel">139****6789</div>
    </div>
    ...省略N个同结构内容...
    <div class="item">
        <div class="name">未知名</div>
        <div class="tel">139****1235</div>
    </div>
</div>
<div class="btn">开始抽奖</div>

<script>
//JSON格式
var md = [
    {
        'name': '张三',
        'tel': '13912356789'
    },
    {
        'name': '李在仁',
        'tel': '15856795625'
    },
    {
        'name': '张学友',
        'tel': '18539251256'
    },
    {
        'name': '刘德华',
        'tel': '15715637855'
    },
    {
        'name': '郭富城',
        'tel': '18912375682'
    },
    {
        'name': '黎明',
        'tel': '13015678535'
    },
    {
        'name': '张曼玉',
        'tel': '17756775275'
    },
    {
        'name': '周润发',
        'tel': '17859653255'
    },
    {
        'name': '未知人士',
        'tel': '15325262799'
    },
    {
        'name': '随机用户',
        'tel': '15327856157'
    },
]
</script>
阅读 2k
2 个回答

第一步可以把md随机打乱,比较随机的算法就是洗牌算法,可以网上看看,下面给一个比较简单的伪随机方法

md.sort(_ => Math.random() < 0.5 ? 1 : -1)

第二步取md的前n个或者后面n个

let list = md.slice(0, 5)

第三步把list渲染到页面,vue就用for循环就行,jq写法

$('.box').html(list.reduce((html, item) => html + `<div class="item">
    <div class="name">${item.name}</div>
    <div class="tel">${item.tel}</div>
</div>`, ''))

这样试试

class Choujiang {
  cacheList = [];
  todos = [];
  deleteIndex = null;

  constructor(list) {
    this.cacheList = list;
  }
  // 抽奖
  choujiang() {
    if (this.deleteIndex !== null) {
      this.todos.splice(this.deleteIndex, 1);
    }
    const count = this.todos.length - 1;
    if (count < 0) {
      console.log("所有用户都中过奖了");
      // 重来
      this.todos = [...this.cacheList];
      this.deleteIndex = null;
      return this.choujiang();
    }
    const index = Math.round(count * Math.random());
    this.deleteIndex = index;

    console.log(this.todos[index].name + "中奖了");

    return this.todos[index];
  }

  // 打乱数据
  getLuanArr() {
    // 上面的回答 md.sort(_ => Math.random() < 0.5 ? 1 : -1)的确更简单
    let i = this.cacheList.length - 1;
    let newSortArr = [];
    while (i >= 0) {
      const item = this.choujiang();
      newSortArr.push(item);
      i--;
    }
    return newSortArr;
  }
}

export default Choujiang;

看看是不是这个效果:https://codesandbox.io/s/chou...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题