2016-02-20 2 views
0

Это еще одно домашнее задание. Мне нужно немного помочь доработать. Что должно произойти, так это то, что JavaScript просматривает заголовки и создает список. Я больше всего закончил. Мне просто нужна помощь в нескольких вещах. Например: какой ID я помещаю в элемент «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 действует как переменная без объявления объявлением 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> 
+0

Вы должны технически поставить 'for (var a = ....) ', но javascript немного снисходит в этом, поэтому вы можете избежать этого в этом случае. Другими словами, да 'a' является переменной _actual_, а не просто действует как единое целое. – Rhumborl

ответ

0

объяснения о том, почему я сделал то, что я сделал будет в нижней

// References the only "<ul>" in the document. 
 
var list = document.getElementById("tableOfContents"); 
 
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 (var a = 1; a <= 10; a++) { 
 
    (function(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"). 
 
    var headingText = document.getElementById(a).innerHTML; 
 
    // c. Create a new <li> element and assign it as the value of the "TOCEntry" variable. 
 
    var TOCEntry = document.createElement ("li"); 
 

 
    // d. Set the content of the "TOCEntry" Node to the following: "<a href=#" + i ">" + headingText + "</a>". 
 
    TOCEntry.innerHTML = "<a href=\"#" + a + "\">" + headingText + "</a>"; 
 
    // e. Add the "TOCEntry" Node as the last child to the list Node. 
 
    list.appendChild (TOCEntry); 
 
    })(a); 
 
} 
 
} 
 
// Backwards-compatibility event listener 
 
if (window.addEventListener) { 
 
window.addEventListener ("load", createTOC, false); 
 
} 
 
else if (window.attachEvent) { 
 
window.attachEvent ("onload", createTOC); 
 
}
<article> 
 
<h2>United States Bill Of Rights</h2> 
 
<h3>Table Of Contents</h3> 
 
<ul id="tableOfContents"> 
 
<!-- 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>

  • [getElementsByTagName][1] возвращает HTMLCollection, а не элемент, поэтому его использование для получения TOC было бы работоспособным, если бы явным образом извлекал первый элемент. (вот почему я дал TOC идентификатор)
  • В комментарии упоминается, что для циклов без ключевого слова var не следует использовать, но не было объяснено, почему: Когда ключевого слова var нет, JS обрабатывает имя как хотя он относится к существующей переменной (так как обычно используются переменные без этого ключевого слова). Когда JS поднимается вверх по лексической иерархии, она в конечном итоге достигает window, где она будет создавать переменную под этим именем, если она не существует. В этом конкретном случае это не является большой проблемой, но если вы когда-либо сталкиваетесь с большим количеством параллелизма (что очень часто встречается в JS), то петли for могут легко начинать ходить друг над другом.
  • так называемая анонимная функция в цикле for существует так, что каждая итерация цикла лексически отделена от других, так что переменные TOCEntry не сталкиваются. (заголовокText - это примитивная строка и поэтому будет передаваться по значению, поэтому риск столкновения не будет.) (Кроме того, прослушиватели событий теперь будут вести себя более интуитивно, вместо того, чтобы все они ссылались на последнее значение a, открытое закрытием)
  • Идентификаторы заголовков были последовательными таким образом, чтобы ваша петля проходила через них, поэтому document.getElementById(a) выберет ту, которая коррелирует с итерацией, в которой она была вызвана.

Кроме того, i является псевдонимным именем для итератора; он должен в значительной степени быть первым итератором, к которому вы идете (это у вашего учителя, хотя именно поэтому его нет в списке.)

+0

Прошу прощения, потребовалось столько времени, чтобы принять этот ответ. Я думал, что знаю. Большое спасибо. –

Смежные вопросы