2013-10-24 48 views
0

我的第一個數組,我認爲會很簡單,但不是(儘管我對js的知識相當簡單)。將html更改爲數組中的下一項 - jquery

我想遍歷點擊事件中的數組(按順序)。所以,在前端,你會看到一個事實,你會點擊一個按鈕來查看下一個事實......簡單的想法。

問:當它全部正常工作時,在數組的末尾,當用戶單擊以查看下一個時會發生什麼?我將如何去處理這個問題?

JS

$(document).ready(function() { 
    function factsInit() { 
     // Define all facts 
     var factText = [ 
       "Oxford won the first Boat Race, which took place on 10th June 1829 at Henley-on-Thames.", 
       "In 2003, Oxford won the closest ever Boat Race by just one foot.", 
       "Oxford coxswain Sue Brown became the first woman to participate in The Boat Race in 1981.", 
       "Oxford's victorious 2009 Blue Boat was the heaviest in the history of the race at an average of 15st 9lb 13oz (99.7kg) per rower.", 
       "In 2012, Oxford's reserve crew, Isis, beat Goldie by 5 lengths to set the course record for the reserve race at 16:41." 
      ], 
      factImage = [ 
       "/clients/oubc/assets/img/factimage_firstrace.jpg", 
       "/clients/oubc/assets/img/factimage_oubc2003.jpg", 
       "/clients/oubc/assets/img/factimage_oubcsuebrown.jpg", 
       "/clients/oubc/assets/img/factimage_oubc2009heaviestever.jpg", 
       "/clients/oubc/assets/img/factimage_isis2012.jpg" 
      ]; 

     // Apply these facts 
     $('#widget_facts .fact_text').html(factText[0]); 
     $('#widget_facts .fact_image > *').attr('src', factImage[0]); 

     // Go to next fact on click 
     $('#widget_facts .link > a').click(function() { 
      $('#widget_facts .fact_text').html(factText++); 
      $('#widget_facts .fact_image > *').attr('src', factImage++); 
     }); 
    } 
    // Run the first fact 
    factsInit(); 
}); 
+0

什麼問題正是 –

+0

@BharathRallapalli'$( '#widget_facts .fact_text')HTML(factText ++);' – rorypicko

+0

^恰好返回NaN –

回答

2

基本上你想增加一個計數器變量,並用它來訪問你有排列的指標。

//declare the counter var 
var factCounter = 0; 

//setup event handler for click event 
$('#widget_facts .link > a').click(function() { 

    //change the text based on the current counter value 
    $('#widget_facts .fact_text').html(factText[factCounter]); 

    //change the image based on the current counter value 
    $('#widget_facts .fact_image > *').attr('src', factImage[factCounter]); 

    //increment the counter var for next time 
    factCounter++; 

    //if the counter var is too large for the number of indexes we've got to work with 
    if (factCounter >= factText.length) { 

     //start over at zero 
     factCounter = 0; 
    } 
}); 

您還可以,如果你開始的第一個表現,並希望顯示在第一次點擊第二個索引更新值之前把factCounter增量代碼。

由於數組是零索引的,因此檢查計數器是否大於或等於索引數基本上是檢查索引是否存在。如果當前計數器值等於索引數量,則不存在計數器值的索引(由於從零開始而不是一個)。

+0

Ahhhh我明白了,所以用'factText ++'我是用一個整數?有道理,像夢一樣工作。謝謝 –

+0

@M_Willett'factText ++'沒有任何意義。你不能增加一個數組,並且這樣做不會增加數組的一些內部指針。 '++'是增加整數。 – Jasper

+0

@M_Willett這裏是關於JS數組的一些很棒的文檔。它會告訴你關於對象與數組以及大量好的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array – Jasper