我正在尝试从https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON调整json-hero教程文件。我不需要一份“权力”的列表。我想将其显示为带换行符的短文本。我用document.createElement('br')替换了document.createElement('li')。为什么来自.json文件(superheroes.json)的document.createElement('br')不显示而只是隐藏?(如果使用document.createElement('p')进行替换,则显示为OK。) https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json脚本如下:
<script>
const header = document.querySelector('header');
const section = document.querySelector('section');
let requestURL = 'superheroes.json';
let request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function() {
const superHeroes = request.response;
populateHeader(superHeroes);
showHeroes(superHeroes);
}
function populateHeader(obj) {
const myH1 = document.createElement('h1');
myH1.textContent = obj['squadName'];
header.appendChild(myH1);
const myPara = document.createElement('p');
myPara.textContent = 'Hometown: ' + obj['homeTown'] + ' // Formed: ' + obj['formed'];
header.appendChild(myPara);
}
function showHeroes(obj) {
const heroes = obj['members'];
for(let i = 0; i < heroes.length; i++) {
const myArticle = document.createElement('article');
const myH2 = document.createElement('h2');
const myPara1 = document.createElement('p');
const myPara2 = document.createElement('p');
const myPara3 = document.createElement('p');
//const myList = document.createElement('ul'); > replaced by:
const myDiv = document.createElement('div');
myH2.textContent = heroes[i].name;
myPara1.textContent = 'Secret identity: ' + heroes[i].secretIdentity;
myPara2.textContent = 'Age: ' + heroes[i].age;
myPara3.textContent = 'Superpowers:';
const superPowers = heroes[i].powers;
var x = "";
for(let j = 0; j < superPowers.length; j++) {
//const listItem = document.createElement('li'); > replaced by br
//problem - the following is hidden and not displayed:
const newlineItem = document.createElement('br');
newlineItem.textContent = superPowers[j];
myDiv.appendChild(newlineItem);
}
myArticle.appendChild(myH2);
myArticle.appendChild(myPara1);
myArticle.appendChild(myPara2);
myArticle.appendChild(myPara3);
//content of myDiv is hidden - why?
myArticle.appendChild(myDiv);
section.appendChild(myArticle);
}
}
</script>发布于 2020-12-11 22:01:48
你遇到这个问题是因为br标签没有显示在屏幕上,如果你检查你的代码,你应该会看到像<br>Content of superPowers[j]</br>这样的东西,但它在你的屏幕上看不到。
要获得您想要的结果,您可以尝试使用p标记更改br标记(如果您想返回到下一个superPower中的下一行),或者使用span标记(如果您想将您的superPowers放在同一行中)。
您的代码应如下所示:
//each element in a new line method
const newlineItem = document.createElement('p');
newlineItem.textContent = superPowers[j];
myDiv.appendChild(newlineItem);
//same line method
const newlineItem = document.createElement('span');
newlineItem.textContent = superPowers[j];
myDiv.appendChild(newlineItem);https://stackoverflow.com/questions/65251942
复制相似问题