如何使用数组更改单击时的图像源?

时间:2014-07-02 00:22:59

标签: javascript

我正在尝试使用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', '');

如何使用cardIndex作为值从我的源数组中获取src?

谢谢!

3 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

src更改为与cardIndex对应,就像您对说明和标题所做的那样:

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

如果你没有jQuery:

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

答案 2 :(得分:0)

向小提琴添加jQUery应解决此问题