javascript - 如何在 Polymer 中随机化 div 的显示顺序
问题描述
我正在尝试随机化 Polymer 中 div 的显示,但是在将这篇文章翻译成框架时遇到了麻烦。
ready() {
super.ready();
let cards = this.shadowRoot.querySelectorAll('.className');
for(var i = 0; i < cards.length; i++){
let target = Math.floor(Math.random() * cards.length -1) + 1;
let target2 = Math.floor(Math.random() * cards.length -1) +1;
cards.eq(target).before(cards.eq(target2));
}
调用时失败cards.eq
...
这可以解决dom-repeat
吗?
解决方案
您链接的解决方案使用 jQuery 选择div
s 而在您的情况下cards
,作为本机querySelector
调用的结果,没有eq
andbefore
方法。
这可以解决
dom-repeat
吗?
是的:您可以将数据模型存储在 div 后面的属性中,并在渲染 div 之前对其进行洗牌:
<dom-module id="my-view">
<template>
<!-- Render the divs using dom-repeat -->
<template is="dom-repeat" items="[[divs]]">
<div>{{item.name}}</div>
</template>
</template>
<script>
class MyView extends Polymer.Element {
static get is() { return 'my-view'; }
static get properties() {
return {
divs: {
type: Array,
value: [],
}
};
}
// In connectedCallback you can initialise the divs property
// by shuffling the initial ordered array using the Fisher-Yates algorithm
// https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
connectedCallback() {
super.connectedCallback();
let array = [ // The ordered model behind the divs
{ name: 'Div #1' },
{ name: 'Div #2' },
{ name: 'Div #3' },
{ name: 'Div #4' },
{ name: 'Div #5' },
];
let currentIndex = array.length, temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
this.divs = array;
}
}
window.customElements.define(MyView.is, MyView);
</script>
</dom-module>
推荐阅读
- django - uwsgi静态文件加载错误表单django(react和webpack)
- android - firebase 数据库和存储为图像返回 null
- r - 如果任何条目在 R 中的数据帧中是无限的,则删除组
- php - "rest_invalid_handler","message":"路由的处理程序无效"
- azure - AKS 日志格式已更改
- ios - 如何在触发 didSelectRowAt 操作和取消选择 tabelview 单元格之前添加一点延迟
- git - 如何为所有开发人员配置 git 钩子
- algorithm - 使用最多 3/2n 比较找到数组中两个元素之间的最大差异
- angular - Angular,@ViewChild 在构造函数/ngOninit 中子组件的值发生变化时不会更新
- mysql - SQL 查询从表 1 中获取 2 个值并连接表 2 中的所有可能选项