1 回答
TA贡献1880条经验 获得超4个赞
使用对象数组跟踪多个计时器的简单演示。只需确定一个易于使用的格式良好的结构来表示数据模型即可。无论是类或函数还是普通对象。
我强烈建议重构你的字符串构建。特别是通过字符串串联生成的JavaScript代码。理想情况下,您需要跟踪计时器,startTimer应该返回这些计时器,并且应该可以与数据结构合并并转换以表示每个计时器。
现在看来,你最终可能会转向使用全局变量来传递参数。
如果这只是一个简单的任务,那么保留一个全局计时器列表可能没什么大不了的。onclick=
tag = (x,y,z)=>`<${x} ${y||''}>${z||''}</${x}>`
function startTimer(duration, display) {
var timer = duration;
var minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
var writeSum = function(sums, champ){
var height = "height: 25px;";
var width = "width: 25px;";
var size = "background-size: 25px 25px;";
var image = "background-image: url( '../../icons/summoner spells/"+sums.path + "\' );";
var display = "display: inline;";
var click = "onclick =\"startTimer("+ sums.cd+", document.getElementById('"+ champ.name+ sums.name+"'\)\)\" ";
return tag("div","",tag("button", click+style(height+width+image+size),"")+ tag("p","id = \""+champ.name+ sums.name + "\" "+style(display),"Ready"));
};
function style(x){return `style="${x}"`}
let entities = [
{sums: {path:'spath1',cd:'10',name:'sname1'}, champ: {name:'cname1'}},
{sums: {path:'spath2',cd:'10',name:'sname2'}, champ: {name:'cname2'}},
{sums: {path:'spath3',cd:'10',name:'sname3'}, champ: {name:'cname3'}},
{sums: {path:'spath4',cd:'10',name:'sname4'}, champ: {name:'cname4'}}
]
document.body.innerHTML=entities.map(({sums, champ})=>writeSum(sums, champ)).join('')
展开代码段
添加回答
举报