遍历数组出错

时间:2018-07-20 09:34:41

标签: javascript jquery

我正在尝试制作一个简单的“应用程序”,通过该应用程序,单击按钮时,h1变为存储在数组中的一个笑话之一。 JS代码如下:

var jokes = [
    "Knock knock. Who’s there? Cow says. Cow says who? No, a cow says mooooo!",
    "Knock knock. Who’s there? Etch. Etch who? Bless you, friend."
]

jokes.forEach(function(item, index, array){
    $('.btn').click(function(){
       document.querySelector('.h1').innerHTML = jokes;  
    });
})

有功能,但是我认为我的逻辑有些混乱。每当我单击按钮时,h1就会更改为数组中的每个笑话,而不是一次更改一次,我该如何解决这个问题?非常感谢您的宝贵时间!

2 个答案:

答案 0 :(得分:-1)

您可以只使用jQuery,而无需混合香草。

通过在每次单击中选择一个随机数组,每次可以显示1个笑话:

Fiddle example using if..else statement

随机建议:

var jokes = [
  "Knock knock. Who’s there? Cow says. Cow says who? No, a cow says mooooo!",
  "Knock knock. Who’s there? Etch. Etch who? Bless you, friend."
]

$('.btn').click(function() {
  var random_index = Math.floor(Math.random() * jokes.length) + 0;
  $('.h1').html(jokes[random_index]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button" class="btn">CHANGE</button>
<h1 class='h1'>INITIAL H1</h1>

if..else建议:

var joke_index = 0;
var jokes = [
  "Knock knock. Who’s there? Cow says. Cow says who? No, a cow says mooooo!",
  "Knock knock. Who’s there? Etch. Etch who? Bless you, friend."
]

$('.btn').click(function() {

  if (joke_index === jokes.length - 1)
    joke_index = 0;
  else
    joke_index++;

  $('.h1').html(jokes[joke_index]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button" class="btn">CHANGE</button>
<h1 class='h1'>INITIAL H1</h1>

答案 1 :(得分:-1)

您可以使用JQ的text方法来解决此问题: 以下代码工作正常。您只需要将随机数传递给索引,以便每次单击按钮时它将替换该值。

var jokes = [
    "Knock knock. Who’s there? Cow says. Cow says who? No, a cow says mooooo!",
    "Knock knock. Who’s there? Etch. Etch who? Bless you, friend."
]

jokes.forEach(function(item, index, array){
    $('.myBtn').click(function(){
       $('.myClass').text(jokes[0]);  
    });
})