如何用一个按钮切换div的多个内容

时间:2019-11-28 10:38:25

标签: javascript

我想创建一个div,它的内容(文本)将在每次单击按钮时更改-但不是作为切换键而是随着多个文本更改而更改。

我有14个句子-当时只需要陈述一个句子。通过单击按钮将显示下一个句子,依此类推。在第14句话之后,我希望它循环回到第一个句子。

您知道如何处理吗? 我发现的所有类似帖子都是关于如何切换两个不同的文本-我需要多个。

我需要的一个很好的例子-检查此site

的页脚

3 个答案:

答案 0 :(得分:3)

您可以声明一个代表句子编号的数字,在单击按钮时将其递增,并显示第i个句子模数句子数组的长度,以产生 loop 效果。像这样:

var sentences = ['first', 'second', 'third', 'fourth'];
var senNum = 0;
var sen = document.getElementById('sen');

sen.innerText = sentences[senNum++]; // set initial sentence
document.getElementById('change').addEventListener('click', function(e) {

  sen.innerText = sentences[senNum++ % sentences.length];
});
<div id='sen'></div>
<button id="change">Change</button>

答案 1 :(得分:0)

您可以将文本存储在数组中吗?

var text = [
  'The road goes ever on and on',
  'Down from the door where it began',
  'Now far ahead the Road has gone',
  'And I must follow if I can'
];

var button = document.getElementById('change-text');
var div = document.getElementById('my-div');
var textIndex = 0;

button.addEventListener('click', function() {
  //Clear current text
  div.innerHTML = '';
  //Create new text node and add text from your array
  var p = document.createElement("p");
  var textnode = document.createTextNode(text[textIndex]);         
  p.appendChild(textnode);

  //Add text to the div                              
  div.appendChild(p);

  //If index is at the end of the array, cycle back to the beginning
  if (textIndex > text.length()) {
    textIndex = 0;
  } else {
    //Or just increment by 1
    textIndex += 1;
  }
});


答案 2 :(得分:0)

简单快捷的纯JavaScript

var cnt = 0;
function callMe(){
var Your_Sentences_Array = 

['Sentences1', 'Sentences2', 'Sentences3', 'Sentences4', 'Sentences5', 'Sentences6', 'Sentences7'];

var div = document.getElementById('idtxt');
div.innerHTML = Your_Sentences_Array[cnt];

cnt == Your_Sentences_Array.length-1 ? cnt = 0 : cnt++ ;
}
<div id="idtxt"></div>
<button type="button" onclick="callMe()">Click for change</button>