在javascript数组元素之间添加换行符

adding line breaks between javascript array elements

本文关键字:添加 换行符 之间 数组元素 javascript      更新时间:2023-09-26

我想知道是否有人能帮助完成这项任务;我发现了这个很好的日常引用代码,我只是想在日常引用和引用的作者之间划一条线。我想创建一个二维数组可能会更容易,但不幸的是,我不知道如何放置换行符。非常感谢。这是迄今为止的代码:

<script type="text/JavaScript"> 
var quote = new Array()
for (i=0; i<7; i++){
quote[i] = new Array(6)
}
quote[0][0] = 'If you want to go fast go alone, if you want to go far go together!'; 
quote[0][1] = 'African Proverb';
quote[1][0] = 'We either make ourselves happy or miserable. The amount of work is the same.'; 
quote[1][1] = 'Carlos Castaneda'; 
quote[2][0] = 'Everything should be made as simple as possible, but not any simpler.'; 
quote[2][1] = 'Albert Einstein';
quote[3][0] = 'Failure is the mother of success.'; 
quote[3][1] = 'Chinese Proverb'; 
quote[4][0] = 'The first to apologize is the bravest. The first to forgive is the strongest. The first to forget is the happiest.' 
quote[4][1] = 'Unknown';
quote[5][0] = 'If an egg is broken by an outside force, life ends. If it is broken by an inside force life begins. Great things happen from the inside.'; 
quote[5][1] = 'Unknown';
quote[6][0] = 'Simplicity is the ultimate sophistication.' 
quote[6][1] = 'Leonardo Da Vinci';
var qlen = quote.length;
var firstDate = new Date(2016,2,25);//start date (yyyy,m,d) - m=0=January, m=1=February
var today = new Date();//today
var dif = Math.floor((today-firstDate)/1000/60/60/24);//difference in days
while(dif>=qlen){//calculate the index of the quote of the day 
dif=dif-qlen;//restart the array index if the difference is greater that the    array's length 
} 
var todayQuote = quote[dif][0];//the quote of the day 
var todayQuoteOwner = quote[dif][1];//author of the quote of the day
onload = function(){document.getElementById('q').firstChild.data = todayQuote + </n>  + document.getElementById('qu').firstChild.data = todayQuoteOwner}

</script> 
<div>  id='q'; </div>  

我建议的第一件事是将<script></script>内容移动到末尾而不是开头,这样就不需要onload函数。

你的javascript也引用了一个qu元素,但你的html代码没有包含它。目前我假设它只是另一个div,但如果我错了,请随时纠正我。

您的javascript似乎还将引号和作者设置为firstChild.data,但您的htmldiv中没有任何子级。因此,如果你真的要运行这个,就会出现一个null错误,因此我为每个添加了一个嵌套的<p />。为了进行测试,我还包含了innerHTML,这样您就可以看到结果。

<div id="q"><p></p></div>
<div id="qu"><p></p></div>
<script type="text/JavaScript">
    // ... generate the quotes and authors ...
    var qElement = document.getElementById('q');
    var quElement = document.getElementById('qu');
    qElement.firstChild.innerHTML = qElement.firstChild.data = todayQuote;
    quElement.firstChild.innerHTML = quElement.firstChild.data = todayQuoteOwner;
</script>

如果您只想为引用和作者提供一个元素容器,那么只需完全去掉qu元素,并用< br/>元素将这两部分分开即可。

<div id="q"><p></p></div>
<script type="text/JavaScript">
    // ... generate the quotes and authors ...
    var qElement = document.getElementById('q');
    qElement.firstChild.innerHTML = qElement.firstChild.data = todayQuote + '<br/>' + todayQuoteOwner;
</script>