我如何继续循环我的函数,所以当在元素中输入新字符串时,它仍然运行相同的函数。
我遇到的问题是,在完成所有最初在html中的字符串之后,它停止了。输入新字符串后,它将不会运行该函数。
function generator() {
string = "Job No.5 [M] [200] [C]";
elems = document.getElementsByClassName("working1");
if (elems[0].innerHTML === ''){
elems[0].innerHTML = string;
}
}
function mover() {
paras = Array.from(document.querySelectorAll('.working1'));
jobelement = document.getElementById("jobend");
for (const para of paras) {
if (para.innerHTML) {
machinetext = para.textContent;
let words = machinetext.split(' ');
let mymachine = words[2];
let myquantity = words[3];
let machinetype = mymachine.slice(1,-1);
let quantityvalue = myquantity.slice(1,-1);
let times1 = quantityvalue * 100;
setTimeout(function() {
jobelement.innerHTML = para.textContent;
console.log(quantityvalue);
para.textContent = "";
generator();
}, times1);
}
}
}
mover();
<p id="machine1" class="working1">Job No.100 [L&M] [200] [D]</p>
<p id="machine2" class="working1">Job No.52 [L] [100] [D]</p>
<p id="machine3" class="working1">Job No.35 [M] [50] [C]</p>
<p id="machine4" class="working1">Job No.5 [L&M] [200] [C]</p>
<p>------------------------------<p>
<p id="jobend" class="jobends"></p>
实际结果-检查元素内字符串中的所有数字。根据该编号延迟下一个功能。将字符串移动到jobend
元素。之后,所有最初存在的字符串均已处理,然后停止。
预期结果-检查元素内字符串中的所有数字。根据该编号延迟下一个功能。将字符串移动到jobend
元素。每当在这些元素之一中输入新字符串时,请继续运行该函数。
答案 0 :(得分:0)
我通过从html分离作业数据来更改您的“体系结构”(在您的代码段中,我们必须等待20秒才能运行第一份作业,因此我将这次除以10(但您可以在最后的{{1}中进行更改) }函数行)。在每个职位描述的mover
数组中,我使用const jobs
代替时间,但是我替换了这个,并在[xxx]
中放置了正确的工作时间。
printJob
const jobs = [
{ name: `Job No.100 [L&M] [xxx] [D]`, time: 200 },
{ name: `Job No.52 [L] [xxx] [D]`, time: 100 },
{ name: `Job No.35 [M] [xxx] [C]`, time: 50 },
{ name: `Job No.5 [L&M] [xxx] [C]`, time: 200 }
]
const newJob = {
name: `Job No.5 [M] [xxx] [C]`,
time: 200
}
function printJobList(jobList) {
document.querySelector('.jobList').innerHTML = "";
jobList.forEach(j => printJob(j, '.jobList'));
}
function printJob(job, selector) {
document.querySelector(selector).innerHTML +=
`<p id="machine1" class="working1">${job.name.replace("[xxx]","["+job.time+"]")}</p>`;
}
function makeJob(job) {
// run job here
console.log(job.time);
document.querySelector('.jobends').innerHTML = "";
printJob(job, '.jobends');
}
function mover(jobs) {
printJobList(jobs);
let job = jobs.shift();
setTimeout(function() {
makeJob(job)
if (jobs.length == 0) jobs.push(newJob) // add job if jobList is empty
mover(jobs);
}, job.time * 10); // here is your "times1"
}
mover(jobs);