【发布时间】:2016-02-20 18:49:49
【问题描述】:
这是另一项家庭作业,我需要一些帮助才能完成。需要发生的是 JavaScript 查看标题并创建一个列表。我已经完成了大部分。我只是需要一些帮助。例如:我在项目“b”中输入了什么 ID,如说明中所说的 Set the value of the "headingText" variable to the content of the element with an ID = to the current value of the counter variable。这是否意味着a 可以作为一个变量而不必用var 声明?感谢您的帮助。
HTML
<article>
<h2>United States Bill Of Rights</h2>
<h3>Table Of Contents</h3>
<ul>
<!-- The Table Of Contents will appear here. -->
</ul>
<h3 id="1">Amendment I</h3>
<p>Congress shall...</p>
<h3 id="2">Amendment II</h3>
<p>A well regulated Militia...</p>
<h3 id="3">Amendment III</h3>
<p>No Soldier shall...</p>
<h3 id="4">Amendment IV</h3>
<p>The right of the people...</p>
<h3 id="5">Amendment V</h3>
<p>No person shall be held...</p>
<h3 id="6">Amendment VI</h3>
<p>In all criminal prosecutions...</p>
<h3 id="7">Amendment VII</h3>
<p>In Suits at common law...</p>
<h3 id="8">Amendment VIII</h3>
<p>Excessive bail shall...</p>
<h3 id="9">Amendment IX</h3>
<p>The enumeration in the Constitution...</p>
<h3 id="10">Amendment X</h3>
<p>The powers not delegated to the...</p>
</article>
JavaScript
<script type="text/javascript">
var TOCEntry = "";
// References the only "<ul>" in the document.
var list = document.getElementsByTagName ("ul");
var headingText= "";
var TOCEntry = "";
function createTOC () {
// a. This counter will = "1", and will repeat the loop as long as the value is LTG "10", and will increment the counter variable by "1" each time through.
for (a = 1; a <= 10; a++) {
// Within the "for" loop, add statements that do the following:
// b. Set the value of the "headingText" variable to the content of the element with an ID = to the current value of the counter variable ("a").
document.getElementById ("___").innerHTML = headingText;
// c. Create a new <li> element and assign it as the value of the "TOCEntry" variable.
var TOCEntry = document.createElement ("li");
document.body.appendChild (TOCEntry);
// d. Set the content of the "TOCEntry" Node to the following: "<a href=#" + i ">" + headingText + "</a>".
var TOCEntry = document.getElementsByTagName ("li").textContent = "";
// e. Add the "TOCEntry" Node as the last child to the list Node.
}
}
// Backwards-compatibility event listener
if (window.addEventListener) {
window.addEventListener ("load", createTOC, false);
}
else if (window.attachEvent) {
window.attachEvent ("onload", createTOC);
}
</script>
【问题讨论】:
-
从技术上讲,您应该输入
for(var a = ....),但 javascript 在这方面有点宽容,因此在这种情况下您可以侥幸逃脱。换句话说,是的,a是一个实际变量,而不只是充当一个变量。
标签: javascript nodes appendchild getelementsbytagname