如何循环遍历数组并在jquery中单击一个类打印出元素?

时间:2016-05-09 18:13:28

标签: javascript jquery html css3

当单击div #background时,数组具有我想要在屏幕上逐个显示的值,但是当单击它时生成新元素时淡出。现在它产生了元素,但它们不会消失而且不会消失?我正在使用jquery,对此非常新!

$(document).ready(function(){
        var arr = ["hello", "hi", "what is up"];
        $.each(arr, function(i, val){
            $("#background").click(function(){
            var element = "<h1>" + val + "</h1>";
            $(".contain").fadeIn("slow").append(element);
            $(element).remove();
            });
      });
    });

2 个答案:

答案 0 :(得分:0)

尝试只设置一次回调:

$(document).ready(function(){
    var arr = ["hello", "hi", "what is up"];
    var i = 0;
    $("#background").click(function(){
        var element = $( "<h1 style='display:none'>" + arr[i] + "</h1>" );
        $(".contain").html(element);
        element.fadeIn("slow")
        i =(i+1)  % arr.length;
    });
});

HTML

<body>
<div id='background'>  <div class="contain">  click me  </div> </div>
</body>

点击here以运行实例。

答案 1 :(得分:0)

这个想法是你将从数组中一次显示一个元素。计数器将计算以循环方式显示的元素数量(意味着一旦显示数组中的所有元素,它将重置为第一个元素)。您将需要以下代码:

HTML:

<div id="background">
  <div class="contain">
    <div></div>
  </div>
</div>

<强> CSS:

#background {
  height: 500px;
}

.contain {
  height: 200px;
  background-color: #ccc;
}

jQuery:

$(document).ready(function() {
  var arr = ["hello", "hi", "what is up"];
  var currentKey = 0;
  $("#background").click(function() {
    //alert("CurrentKey : " + currentKey);
    $(".contain").html(" " + arr[currentKey] + " ").hide().fadeIn(600);
    if (currentKey === (arr.length - 1)) {
      currentKey = 0;
    } else {
      currentKey = currentKey + 1;
    }
  });
});

您可以运行下面的代码段来查看:

$(document).ready(function() {
  var arr = ["hello", "hi", "what is up"];
  var currentKey = 0;
  $("#background").click(function() {
    //alert("CurrentKey : " + currentKey);
    $(".contain").html(" " + arr[currentKey] + " ").hide().fadeIn(600);
    if (currentKey === (arr.length - 1)) {
      currentKey = 0;
    } else {
      currentKey = currentKey + 1;
    }
  });
});
#background {
  height: 500px;
}

.contain {
  height: 200px;
  background-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="background">
  <div class="contain">
    <div></div>
  </div>
</div>

如果您愿意,也可以JS Fiddle link