2012-07-26 117 views
0

我想在我的HTML頁面中使用倒計時這樣的腳本使用一個倒計時腳本多個倒計時

 var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") 

function countdown(yr,m,d,idCountdown){ 
    var theyear=yr; 
    var themonth=m; 
    var theday=d; 
    var today=new Date(); 
    var todayy=today.getYear(); 
    if (todayy < 1000) 
     todayy+=1900 
    var todaym=today.getMonth(); 
    var todayd=today.getDate(); 
    var todayh=today.getHours(); 
    var todaymin=today.getMinutes(); 
    var todaysec=today.getSeconds(); 
    var todaystring=montharray[todaym]+" "+todayd+", "+todayy+" "+todayh+":"+todaymin+":"+todaysec; 
    var futurestring=montharray[m-1]+" "+d+", "+yr; 
    var dd=Date.parse(futurestring)-Date.parse(todaystring); 
    var dday=Math.floor(dd/(60*60*1000*24)*1); 
    var dhour=Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1); 
    var dmin=Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1); 
    var dsec=Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1); 
    var dag = "dagen"; 

    if(dday==0&&dhour==0&&dmin==0&&dsec==1){ 
     document.getElementById(idCountdown).value=current; 
     return; 
    } 
    else if(dday<=1) { 
     dag = 'dag'; 
    } 
    document.getElementById(idCountdown).value=dday+ ' ' + dag + ' ' +dhour+" uur "+dmin+" min "+dsec+" sec"; 
    setTimeout(function(){countdown(theyear,themonth,theday,idCountdown);}, 1000); 
} 

我會有這樣的

<input name="aktie1" type="text" class="countdownTekst" size="27" readonly="readonly"> 
<input name="aktie2" type="text" class="countdownTekst" size="27" readonly="readonly"> 

然後,我用它來使用文本框功能

countdown(2012,7,30, 'aktie1') 

最後一個是textfield的ID。但是當我這樣做,我會得到一個錯誤

document.forms.count.idCountdown.value is undefined 

如何獲得該函數中的文本字段的id?

回答

1

您需要訪問這樣的輸入:document.forms.count[idCountdown].value

編輯:這撥弄工作http://jsfiddle.net/Fy2FM/4/。更大的問題是你沒有用var yourvar聲明變量,這使變量成爲全局對象的一部分。正因爲如此,你在倒計時中總是看到相同的結果,因爲實際上你正在訪問相同的變量。

+0

感謝。當我這樣做formfields加載的日子等,但它不再倒數了,我得到這個錯誤在FB:TypeError:document.forms.count [idCountdown]是undefined – 2012-07-26 08:38:24

+0

@RickWeller也許問題在這裏:'setTimeout( 「倒數(今天,月,日)」,1000)'。試試這個: 'setTimeout(function(){countdown(theyear,themonth,theday,idCountdown);},1000);' – Vithozor 2012-07-26 08:41:49

+0

這似乎是問題所在。只有當我這樣做,它會加載所有的倒計時,但是當它開始計算它將只使用aktie2日期:( – 2012-07-26 08:47:12

0

凡在此腳本,例如添加具體時間爲:3:44

<script language="javascript">countdown(2016,6,20,15:44 'aktie1')</script>