如何解决Javascript 报价索引器
我已经创建了一个 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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。