问题描述
我已经创建了一个 Javascript 以便如果我在下面的脚本中添加引号,它应该放在 <p></p>
元素中。
const quotes = [
{ quotes: 'Be yourself; everyone else is already taken' },{ quotes: 'So Many Books,So Little Time' },{ quotes: "Strangers think I'm Quiet. My Friends think I'm outgoing. My best friends kNow that I'm Completely Insane" },{ quotes: 'A room without books is like a body without soul' },{ quotes: 'You only live once,but if you do it right,once is enough' },];
function quoteindexer() {
quotesView.innerHTML = quotes[i].quotes;
}
我的 html 代码
<p class="quotes" id="quoteindexer"></p>
但我需要在不同的 <p></p>
元素本身中显示所有引号。也就是说,引号的数量应该等于创建的 <p></p>
的数量。我是 Javascript 新手,所以请帮助我。
解决方法
您需要仔细阅读每个引文并为其创建一个段落:
const quotes = [
{ quotes: 'Be yourself; everyone else is already taken' },{ quotes: 'So Many Books,So Little Time' },{ quotes: "Strangers think I'm Quiet. My Friends think I'm outgoing. My best friends know that I'm Completely Insane" },{ quotes: 'A room without books is like a body without soul' },{ quotes: 'You only live once,but if you do it right,once is enough' },];
var quotesHtml = quotes.map(function(q) {
return '<p class="quotes">'+ q.quotes +'</p>'
}).join('\n');
function quoteindexer() {
quotesView.innerHTML = quotesHtml;
}
,
var quotes = [
{ quotes: 'Be yourself; everyone else is already taken' },once is enough' }
];
function quoteindexer(arrayQ) {
let quotesView = document.getElementById('quotesView'); //target your container
for(var j in arrayQ){
//pass quotes into the container
quotesView.innerHTML +='<p class="quotes">';
quotesView.innerHTML += quotes[j].quotes;
quotesView.innerHTML += '</p>';
}
}
//
quoteindexer(quotes);
<div id='quotesView'></div>
<style>
.quotes{
background: #dde;
border-radius: 5px;
padding: 5px;
margin: 3px;
}
</style>
看看这个
<div id="quotesView"></div>
简单地使用Array.map() 方法。示例:
const quotes = [
{ quotes: 'Be yourself; everyone else is already taken' },once is enough' }
]
let container = document.getElementById("myQuotes")
let Allquotes = quotes.map(myquote =>{
return `<p>${myquote.quotes}</p> \n`
})
container.innerHTML = Allquotes
<div id="myQuotes">
</div>