迭代函数

时间:2017-10-20 12:55:42

标签: javascript loops variables

我的页面上有几个倒计时,我在下面找到了这个脚本,我试图修改以迭代原始脚本,以便我显示几个倒计时。

例如,我在<div id="dateHere1"></div><div id="dateHere2"></div><div id="dateHere3"></div>等进行了倒计时......

这就是为什么我需要使用1到10之间的数字迭代以下函数。如何在函数中为变量名添加字符串str(10)?

var str = 10;

for (i = 0; i < str; i++) { 
    addEventsHereAndThere([i]);

}



function addEventsHereAndThere(number) {
// Set the date we're counting down to
var theCorrectDate.number = document.querySelector('#thisIsTheDate'.number).value;
var countDownDate.number = new Date(theCorrectDate.number).getTime();

// Update the count down every 1 second
var x.number = setInterval(function() {

    // Get todays date and time
    var now = new Date().getTime();
    
    // Find the distance between now an the count down date
    var distance.number = (countDownDate.number) - now;
    
    // Time calculations for days, hours, minutes and seconds
    var days.number = Math.floor(distance.number / (1000 * 60 * 60 * 24));
    var hours.number = Math.floor((distance.number % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes.number = Math.floor((distance.number % (1000 * 60 * 60)) / (1000 * 60));
    var seconds.number = Math.floor((distance.number % (1000 * 60)) / 1000);
    
    // Output the result in an element with id="demo"
	if (days.number == 0 && hours.number == 0 && minutes.number == 0) {
		document.getElementById("dateHere".number).innerHTML = seconds.number + "s";
	} else if (days.number == 0 && hours.number == 0) {
		document.getElementById("dateHere".number).innerHTML = minutes.number + "m " + seconds.number+ "s";
	} else if (days.number == 0) {
		document.getElementById("dateHere".number).innerHTML = hours.number + "t "
    	+ minutes.number + "m " + seconds.number+ "s";
	} else {
    document.getElementById("dateHere".number).innerHTML = days.number+ "d " + hours.number + "t "
    + minutes.number + "m " + seconds.number + "s";
	}
    
    // If the count down is over, write some text 
    if (distance.number < 0) {
        clearInterval(x.number);
		document.getElementById("dateBackgroundHere".number).style = "position:absolute; bottom:0; height:45px; width:100%; background: rgba(230, 47, 47, 0.8); color:#fff; font-family: Fira Sans, sans-serif; font-size: 12px; font-weight: bold; padding-top: 8px;";
        document.getElementById("dateHere".number).innerHTML = "UDLØBET";
    }
}, 1000);
}

1 个答案:

答案 0 :(得分:0)

有两件事情跳出来:

  1. 将函数传递给函数时,不要将其包装在数组中:

    addEventsHereAndThere(i);
    // No [] here --------^
    
  2. 使用时使用有效的JavaScript(非PHP)字符串连接:

    ... = document.querySelector('#thisIsTheDate' + number).value;
    // + not . here ------------------------------^
    
  3. 附注:仅按其ID选择元素时,最好使用getElementById(不使用#,因为它需要ID而不是选择器)而不是querySelector ,所以:

    ... = document.getElementById('thisIsTheDate' + number).value;
    

    他们最终会得到相同的结果,但getElementById要快得多。 (并不是说它可能真的很重要。)