如何使用 for 循环将一段重复的 javascript 打印到 HTML 文档?

Posted

技术标签:

【中文标题】如何使用 for 循环将一段重复的 javascript 打印到 HTML 文档?【英文标题】:How do I print a repeated piece of javascript to a HTML document using a for loop? 【发布时间】:2021-02-23 22:18:09 【问题描述】:

这里的自学爱好者试图创建一个工作表来帮助学生练习联立方程式。 我正在努力解决如何重复运行下面的代码以生成多个问题。

我认为问题在于这里的[i]

document.getElementsByClassName("question")[i].getElementsByClassName("part")[n].innerhtml

有人可以向我解释为什么像这样使用 for 循环变量重复写入 HTML 不起作用,我该如何解决?

非常感谢您的帮助。

<div class="question">
  <ul>
    <li class="part"></li>
    <li class="part"></li>
    <li class="part"></li>
  </ul>
</div>

<div class="question">
  <ul>
    <li class="part"></li>
    <li class="part"></li>
    <li class="part"></li>
  </ul>
</div>



for (i = 0; i < 5; i++)
    var n = 12

    x = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*n))
    y = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*n))
    z = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*n))

    m = 20
    a = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*m))
    b = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*m))
    c = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*m))

    d = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*m))
    e = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*m))
    f = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*m))

    g = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*m))
    h = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*m))
    i = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*m))

    rhs1 = a*x + b*y + c*z
    rhs2=  d*x + e*y + f*z
    rhs3 = g*x + h*y + i*z

    document.getElementsByClassName("question")[i].getElementsByClassName("part")[0].innerHTML= a + " x + " + b + " y + " + z + " z = " + rhs1;
    document.getElementsByClassName("question")[i].getElementsByClassName("part")[1].innerHTML= d + " x + " + e + " y + " + f + " z = " + rhs2;
    document.getElementsByClassName("question")[i].getElementsByClassName("part")[2].innerHTML= g + " x + " + h + " y + " + i + " z = " + rhs3;

  

【问题讨论】:

您可以发布 HTML 代码以供参考吗? 没问题,刚刚加进去了。 啊,问题在于li 元素在ul 元素内,我想我应该可以为您解答 呃,为什么 html 被删除了? 对不起,这太微妙了。您在计算和迭代中使用了相同的变量。你基本上写了以下循环:while(Math.random()*40-20 &lt; 5) ... 【参考方案1】:

试试这个,第一个children[0] 访问ul 元素,第二个children[0 or 1 or 2] 访问该部分,也稍作更改,您可以设置一个等于 document.getElementsByClassName("question") 的变量,这样你就不用'不需要每次都请求它

questions = document.getElementsByClassName("question")
questions[i].children[0].children[0].innerHTML = a + " x + " + b + " y + " + z + " z = " + rhs1;
questions[i].children[0].children[1].innerHTML = d + " x + " + e + " y + " + f + " z = " + rhs2;
questions[i].children[0].children[2].innerHTML = g + " x + " + h + " y + " + i + " z = " + rhs3;

【讨论】:

恐怕运气不好。还是谢谢。 对此进行了测试并且可以正常工作,只是看到它是因为您正在为其中一个问题覆盖i 的值,因此如果您更改@987654326,它会尝试获取超出范围的值@ 到另一个变量它应该可以工作 太棒了,非常感谢。我也会学习.children,看起来很有用。【参考方案2】:

您遇到的问题是您在 for 循环中将 i 称为增量值,但随后您将其值更改为计算值。

我把它改成了cntr

for (cntr=0; cntr<5; cntr++)
var n = 12

    x = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*n))
    y = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*n))
    z = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*n))

    m = 20
    a = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*m))
    b = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*m))
    c = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*m))

    d = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*m))
    e = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*m))
    f = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*m))

    g = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*m))
    h = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*m))
    i = (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*m))

    rhs1 = a*x + b*y + c*z
    rhs2=  d*x + e*y + f*z
    rhs3 = g*x + h*y + i*z

    document.getElementsByClassName("question")[cntr].getElementsByClassName("part")[0].innerHTML= a + " x + " + b + " y + " + z + " z = " + rhs1;
    document.getElementsByClassName("question")[cntr].getElementsByClassName("part")[1].innerHTML= d + " x + " + e + " y + " + f + " z = " + rhs2;
    document.getElementsByClassName("question")[cntr].getElementsByClassName("part")[2].innerHTML= g + " x + " + h + " y + " + i + " z = " + rhs3;

  

【讨论】:

就是这样!非常感谢! .我投了赞成票,但我认为它没有显示,因为这是一个新帐户。 我不会一遍又一遍地得到.question。处理器昂贵。 感谢@StackSlave 的提示。什么是最好的选择?将这些附加到文档中会更好吗? 将可以存储的元素存储在循环和函数之外的变量中,就像我在示例中所做的那样。注意循环外的question【参考方案3】:

提取函数:

function getTriplet(n) 
  return [0, 1, 2].map(_ => (Math.random()<0.5? 1:-1)*(Math.ceil(Math.random()*n)));


const [x, y, z] = getTriplet(12);

console.log(x, y, z);

动态生成 DOM:

function getQuestion(parts) 
  const q = document.createElement('div');
  q.classList.add('question');

  const list = document.createElement('ul');
  for (const part of parts) 
    const item = document.createElement('li');
    item.classList.add('part');
    item.innerText = part;
    list.appendChild(item);
  
  q.appendChild(list);
  return q;


document.body.appendChild(getQuestion(['A', 'B', 'C']));
document.body.appendChild(getQuestion(['1', '2', '3']));

使用字符串模板插值更清晰:

const a = 6;
const b = 7;

document.querySelector('sample').innerText = `$a * $b = $a * b`;
&lt;sample&gt;&lt;/sample&gt;

不要使用全局变量。例如,您正在重用全局 i 进行循环和计算。

【讨论】:

【参考方案4】:

也许你应该研究以下结构:

//<![CDATA[
/* js/external.js */
let doc, htm, bod, nav, M, I, mobile, S, Q, rand, signedRand; // for use on other loads
addEventListener('load', ()=>
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>
  var w = within || doc;
  return w.querySelector(selector);

Q = (selector, within)=>
  var w = within || doc;
  return w.querySelectorAll(selector);

rand = (min, max)=>
  let mn = min, mx = max;
  if(mx === undefined)
    mx = mn; mn = 0;
  
  return mn+Math.floor(Math.random()*(mx-mn+1));

signedRand = (min, max)=>
  return (Math.random() < 0.5 ? 1 : -1)*rand(min, max);

// magic under here - you could put below on a separate page using a load event - execept the end load
const question = Q('.question');
let n, x, y, z, a, b, c, d, e, f, g, h, i, xyz, p;
for(let q of question)
  n = 13; x = signedRand(n); y = signedRand(n); z = signedRand(n);
  n = 21; a = signedRand(n); b = signedRand(n); c = signedRand(n);
  d = signedRand(n); e = signedRand(n); f = signedRand(n);
  g = signedRand(n); h = signedRand(n); i = signedRand(n);
  xyz = S('.xyz', q); p = Q('.part', q);
  xyz.textContent = 'x = '+x+'; y = '+y+'; z = '+z+';';
  p[0].textContent = a+'x + '+b+'y + '+c+'z = '+(a*x+b*y+c*z);
  p[1].textContent = d+'x + '+e+'y + '+f+'z = '+(d*x+e*y+f*z);
  p[2].textContent = g+'x + '+h+'y + '+i+'z = '+(g*x+h*y+i*z);

); // end load
//]]>
/* css/external.css */
*
  box-sizing:border-box; font-size:0; color:#000; padding:0; margin:0; overflow:hidden;

html,body,.main
  width:100%; height:100%;

.main
  background:#333; overflow-y:auto; padding:7px 10px;

.question>div
  color:#fff; font:bold 22px Tahoma, Geneva, sans-serif;

.question>.xyz
  background:#ccc; color:#000; padding:3px 5px; margin-bottom:2px; border-radius:1px;

.question
  padding:7px; border:1px solid #fff; border-radius:2px; margin-bottom:7px;
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
    <title>Title Here</title>
    <link type='text/css' rel='stylesheet' href='css/external.css' />
    <script src='js/external.js'></script>
  </head>
<body>
  <div class='main'>
    <div class='question'>
      <div class='xyz'></div>
      <div class='part'></div>
      <div class='part'></div>
      <div class='part'></div>
    </div>
    <div class='question'>
      <div class='xyz'></div>
      <div class='part'></div>
      <div class='part'></div>
      <div class='part'></div>
    </div>
    <div class='question'>
      <div class='xyz'></div>
      <div class='part'></div>
      <div class='part'></div>
      <div class='part'></div>
    </div>
    <div class='question'>
      <div class='xyz'></div>
      <div class='part'></div>
      <div class='part'></div>
      <div class='part'></div>
    </div>
    <div class='question'>
      <div class='xyz'></div>
      <div class='part'></div>
      <div class='part'></div>
      <div class='part'></div>
    </div>
    <div class='question'>
      <div class='xyz'></div>
      <div class='part'></div>
      <div class='part'></div>
      <div class='part'></div>
    </div>
    <div class='question'>
      <div class='xyz'></div>
      <div class='part'></div>
      <div class='part'></div>
      <div class='part'></div>
    </div>
  </div>
</body>
</html>

【讨论】:

以上是关于如何使用 for 循环将一段重复的 javascript 打印到 HTML 文档?的主要内容,如果未能解决你的问题,请参考以下文章

for循环

Linux基础之bash脚本进阶篇-循环语句(for,while,until)及其特殊用法

shell脚本编程循环之for/while/untill循环

使用 java 8 将一段时间更改为 IntStream

使用for循环将数据帧保存为.Rdata文件[重复]

Bash脚本之循环