Javascript: мой .textContent работает, но не мой innerHTML

У меня странная проблема. В общем, когда я устанавливаю переменную как textContent, она отображается, но не когда я устанавливаю ее как innerHTML

Точнее

Вот HTML

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Dynamic Menu</title>
</head>
<body id="top">
    <h1>The Extremadura Region of Western Spain</h1>
    <h2 >Geography Of The Region</h2>
    <p>The autonomous community of Extremadura is in western Spain alongside the Portuguese border.
    It borders the Spanish regions of Castilla y Leon, Castilla La Mancha and Andalucía as well as Portugal (to the West). 
    Covering over 40,000 square kilometers it has two provinces: Cáceres in the North and Badajoz in the South.</p>

    <h2>Where To Stay</h2>
    <p>There is a wide range of accommodation throughout Extremadura including small inns and guest houses ('Hostals') or 
    think about renting a 'casa rural' (country house) if you are travelling in a group.</p>

    <h2>Climate</h2>
    <p>Generally Mediterranean, except for the north, where it is continental. Generally known for its extremes,
    including very hot and dry summers with frequent droughts, and its long and mild winters.</p>

    <h2>What To See</h2>
    <p>Extremadura hosts major events all year round including theater, music, cinema, literature and folklore. 
    Spectacular venues include castles, medieval town squares and historic centers.
    There are special summer theater festivals in the Mérida, Cáceres, Alcántara and Alburquerque.</p>

    <h2>Gastronomy</h2>
    <p>The quality of Extremaduran food arises from the fine quality of the local ingredients. 
    In addition to free-range lamb and beef, fabulous cheeses, red and white wines, olive oil, honey and paprika,
    Extremadura is particularly renowned for Iberian ham. The 'pata negra' (blackfoot) pigs are fed on acorns in the
    cork-oak forests, the key to producing the world's best ham and cured sausages.</p>

    <script src="lunch.js"></script>
</body>
</html>

Вот сценарий

function lop(){

var hs = document.getElementsByTagName('h2');
for(var g = 0; g<hs.length; g++){
    hs[g].setAttribute('id', g);
}
var budy = document.getElementById('top');   //Gets the body id
var nnn = document.createElement('nav');   //Creats a nav event
var uuu = "<ul >  \
                <li id='one'> <a href='#0'>Geography Of The Region </a> </li>  \
                <li id='two'> <a href='#1'>Where To Stay </a> </li>  \
                <li id='tre'> <a href='#2'>Climate </a> </li>   \
                <li id='for'> <a href='#3'>What To See</a> </li>  \
                <li id='fiv'> <a href='#4'>Gastronomy</a> </li>";
// li: 55-60 make the HTML              
nnn.innerHTML = uuu;     //Sets the HTML to the nav
var h = document.getElementsByTagName('h2')[0]; // Get the specific element
budy.insertBefore(nnn, h);  // inserts the element nav and the whole html before h

var ps = document.getElementsByTagName('p');
var hih = '<a href="#top"> AAAAA </a>';
for(var g = 0; g<ps.length; g++){
    ps[g].nextSibling.innerText = hih;
}

}

lop();  //cals the function so it executes

Итак, в основном в этом упражнении я должен создать ul в скрипте и без изменения HTML.

Мне удалось создать файл ul. Затем я должен создать ссылку, которая приведет меня к началу страницы. Что это за часть здесь:

var ps = document.getElementsByTagName('p');
var hih = '<a href="#top"> AAAAA </a>';
for(var g = 0; g<ps.length; g++){
    ps[g].nextSibling.innerText = hih;
}

Здесь я пытаюсь создать ссылку, которая вернет меня наверх. Я использую то преимущество, что в хроме есть пустое пространство между братом и сестрой, чтобы создать там эту ссылку.

Проблема в том, что он не показывает. Когда я иду в свой отладчик, у меня нет ошибок, но ничего не показывает. Если изменить ps[g].nextSibling.innerText = hih; на .textContent, это покажет всю мысль.

Я знаю разницу между .innerHTML и .textContent (или мне кажется), так почему же он не показывает мою ссылку и могу ли я сделать так, чтобы она показывалась?


person ATrashInTheWorld    schedule 09.03.2017    source источник


Ответы (2)



Итак, мой друг изменил мою процедуру, и вот что он сделал:

var ps = document.getElementsByTagName('p');
var hih = '<br /><br /><a href="#top"> To the top </a> ';

for(var g = 0; g<ps.length; g++) {
    ps[g].innerHTML += hih;
}

Другими словами, за эти 3 часа js я узнал, что вы не можете изменить пустой HTML-код дочернего элемента, а только его текст.

person ATrashInTheWorld    schedule 09.03.2017
comment
мой ответ совпадает с вашим ответом. я этого не понимаю - person Phu Duy; 09.03.2017
comment
Я понял это после, я просто не понял, когда ты объяснил. Мне жаль. - person ATrashInTheWorld; 10.03.2017