2014-07-02 50 views
0

我試圖使用var cardIndex更改圖像的src屬性。如何使用數組更改點擊圖片源?

<button onclick="changeCard()">Draw Card</button> 
<h1 id="theTitle">Click Draw to Begin</h1> 
<p id="theDescription">Just press the button below and experience the fun!</p> 
<img id="theCard" src=""/> 

var cardIndex = 0; 
var cards = [ 
"Card 1", 
"Card 2", 
"Card 3", 
"Card 4", 
]; 

var description = [ 
"Description 1", 
"Description 2", 
"Description 3", 
"Description 4", 
]; 

var source = [ 
"http://cf.geekdo-images.com/images/pic202889.jpg", 
"http://upload.wikimedia.org/wikipedia/commons/thumb/6/63/French_suits.svg/300px-French_suits.svg.png", 
"http://www.leadersinstitute.com/wp-content/uploads/2011/02/playing-cards.jpg", 
"http://i106.photobucket.com/albums/m275/jogi21/marked-playing-cards.jpg", 
] 

function changeCard() { 
    ++cardIndex; 
    if (cardIndex >= cards.length) { 
     cardIndex = 0; 
    } 

    document.getElementById("theDescription").innerHTML =   description[cardIndex]; 
    document.getElementById("theTitle").innerHTML = cards[cardIndex]; 
    $('#theCard').attr('src', ''); 

} 

我無法在這裏找出語法:

$('#theCard').attr('src', ''); 

我怎麼會讓它走SRC使用cardIndex,因爲它的價值我的源陣列?

謝謝!

+0

'$('#theCard')。attr('src',source [cardIndex])'不起作用? – dave

回答

0

更改src像你描述和標題做了對應cardIndex

$('#theCard').attr('src', source[cardIndex]); 

如果你沒有jQuery的:

document.getElementById('thecard').src = source[cardIndex]; 
+0

感謝您的幫助。我試圖插入這個,但img src仍然不會改變。不知道爲什麼。 http://jsfiddle.net/Bum6L/22/ – user3640511

+0

@ user3640511嗯,那是因爲你沒有jQuery。我已經更新了我的答案。 –

+0

謝謝! JavaScript解決方案可行!如果我願意,你介意簡單地解釋或鏈接到如何使用jQuery工作?我試着通過添加這個來嘗試安裝:但是不認爲它有效。 – user3640511

0

這裏是我會怎麼做,再加上一些代碼更改清理了一點東西:

var cardIndex = 0; 
var cards = [ 
    { title: "Card 1", 
    description: "Description 1", 
    source: "http://cf.geekdo-images.com/images/pic202889.jpg" 
    }, 
    { title: "Card 2", 
    description: "Description 2", 
    source: "http://upload.wikimedia.org/wikipedia/commons/thumb/6/63/French_suits.svg/300px-French_suits.svg.png" 
    }, 
    { title: "Card 3", 
    description: "Description 3", 
    source: "http://www.leadersinstitute.com/wp-content/uploads/2011/02/playing-cards.jpg" 
    }, 
    { title: "Card 4", 
    description: "Description 4", 
    source: "http://i106.photobucket.com/albums/m275/jogi21/marked-playing-cards.jpg" 
    }]; 

function changeCard() { 
    ++cardIndex; 
    if (cardIndex >= cards.length) { 
     cardIndex = 0; 
    } 

    var card = cards[cardIndex]; 
    $('#description').html(card.description); 
    $('#theTitle').html(card.title); 
    $('#theCard').attr('src', card.source); 
} 
+0

謝謝!這更清潔。我嘗試過插入這個解決方案,但是由於某種原因它不起作用。這裏是它的jsfiddle:http://jsfiddle.net/Bum6L/21/ – user3640511

0

添加了jQuery小提琴應該會解決這個問題