我在 html 中有 3 张图片,我在我的 js 中通过它们的类获取它们,将它们洗牌,我需要让它们出现在通过洗牌排序的 html 上,但它们永远不会改变。 这是我的 html 代码:
var frontcards = document.getElementsByClassName('cards');
var myCards = [];
myCards.push(frontcards[0]);
myCards.push(frontcards[1]);
myCards.push(frontcards[2]);
Array.prototype.shuffle = function() {
var input = this;
for (var i = input.length - 1; i >= 0; i--) {
var randomIndex = Math.floor(Math.random() * (i + 1));
var itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
return input;
}
var playButton = document.getElementById("play");
playButton.onclick = function() {
myCards.shuffle();
for (var i = 0; i < myCards.length; i++) {
document.getElementsByClassName('cards')[i].innerHTML = myCards[i].src;
}
}
<img class="cards" height="300px" width="200" src="images/card1.jpg">
<img class="cards" height="300px" width="200" src="images/card2.png">
<img class="cards" height="300px" width="200" src="images/card3.png">
我需要 js 来更改 html 上的图像 src。这可能吗?
最佳答案
当您应该设置源时,您试图设置 innerHTML,是的,但是您有另一个可能不明显的问题。 myCards
和 document.getElementsByClassName('cards')
的结果都包含对相同 3 个 img 标签的引用(或实际上是指针),但顺序不同。当您修改其中一个数组中的 src 时,它实际上会更改两个数组中的它,因此您最终会得到重复的源。
可能有一些解决方案需要重构您的代码,但这里有一个不需要。如果您将该元素附加为包含所有卡片的容器的子元素(在下面的代码中我创建了一个,但这取决于您自己的 html 设置),那么它将将该特定卡片移动到容器的末尾.对所有卡片都这样做,然后它们将按洗牌顺序排列。它只是重新排序元素本身,因此您无需担心更改 src(我从下面的示例中删除了它,以便更容易看到它被打乱)
var frontcards = document.getElementsByClassName('cards');
var myCards = [];
myCards.push(frontcards[0]);
myCards.push(frontcards[1]);
myCards.push(frontcards[2]);
Array.prototype.shuffle = function() {
var input = this;
for (var i = input.length - 1; i >= 0; i--) {
var randomIndex = Math.floor(Math.random() * (i + 1));
var itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
return input;
}
var playButton = document.getElementById("play");
playButton.onclick = function() {
myCards.shuffle();
var cards_area = document.getElementById("cards_area")
for (var i = 0; i < myCards.length; i++) {
cards_area.appendChild(myCards[i])
}
}
.cards{
display : inline;
transition : all 1s ease-in-out;
}
.c1{
background-color : red;
}
.c2{
background-color : blue;
}
.c3{
background-color : green;
}
<button id="play">PLAY</button>
<div id="cards_area">
<img class="cards c1" height="300px" width="200">
<img class="cards c2" height="300px" width="200">
<img class="cards c3" height="300px" width="200">
</div>
关于javascript - 在js中洗牌后如何更改html中的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48127978/