[英]How to loop through array and print out elements with a class on click in jquery?
The array has values that i want to display on the screen one by one when the div #background is clicked, but then fade out when it is clicked and produce a new element. 单击div #background时,该数组具有要在屏幕上逐一显示的值,但是单击它时淡出并生成一个新元素。 right now it produces the elements but they dont disappear and do not fadeIn?
现在它会产生元素,但它们不会消失并且不会褪色? I am working with jquery and very new to this!
我正在使用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();
});
});
});
Try to set the callback only once: 尝试仅设置一次回调:
$(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 HTML
<body>
<div id='background'> <div class="contain"> click me </div> </div>
</body>
The idea is that you will show each element one at a time from the array. 这个想法是您将一次显示数组中的每个元素。 A counter will count the number of elements displayed in a circular manner (meaning once it is shown all the elements in the array, it will be reset to the first one).
计数器将对循环显示的元素数进行计数(这意味着一旦显示了数组中的所有元素,它将被重置为第一个)。 You will need the following code :
您将需要以下代码:
HTML : HTML:
<div id="background">
<div class="contain">
<div></div>
</div>
</div>
CSS: CSS:
#background {
height: 500px;
}
.contain {
height: 200px;
background-color: #ccc;
}
jQuery : 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;
}
});
});
You can run the snippet below to see this : 您可以运行下面的代码片段以查看此内容:
$(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>
Here's also a JS Fiddle link if you prefer that. 如果您愿意的话,这也是JS Fiddle链接 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.