JQuery:如何在每次点击时逐个显示段落标签数组?

时间:2016-05-04 16:06:33

标签: javascript jquery

var sentences = ['sentenceone', 'another sentence', 'another sentence again'];

$(".btn").on('click', function() {

    for(var i=0; i < sentences.length; i++) {
        samplebox.innerHTML += '<p>'+sentences[i]+'</p>';
    }
});

只需点击一下即可显示所有这些内容。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:6)

您可以像这样一个一个地显示段落:

var sentences = ['sentenceone', 'another sentence', 'another sentence again'];
var i = 0;

$(".btn").on('click', function() {

  if (i < sentences.length) {
    samplebox.innerHTML += '<p>' + sentences[i] + '</p>';
    i++;
  }

});

答案 1 :(得分:0)

<button class="btn" data-step="1">Click here</button>

var sentences = ['sentenceone', 'another sentence', 'another sentence again'];

$(".btn").on('click', function() {
        var limit = parseInt( $(this).attr("data-step") ) - 1;
        for(var i=0; i < limit; i++) {
            samplebox.innerHTML += '<p>'+sentences[i]+'</p>';
        }
        $(this).attr("data-step") = limit + 2;
    });