我正在构建一个应用程序,当我单击卡片时它会翻转并生成一个随机单词。然后我悬停随机单词。该程序正在调用 responsiveVoice api,传递参数并说出这个词。我的问题是这只适用于第一次。当我再次单击卡片时卡片翻转然后我将鼠标悬停在随机文本上它重复最后一个单词+新单词。知道如何解决javascript数组吗?
var cards = [
{ animal: "Dog", animal_type: "A" },
{ animal: "Pig", animal_type: "B" },
{ animal: "Hippopo", animal_type: "B" },
{ animal: "Cat", animal_type: "A" },
];
const
$card = document.querySelector('.card'),
$demo = document.querySelector('#demo');
let display_text = true;
$card.addEventListener('click', function () {
$card.classList.toggle('is-flipped');
if (display_text) {
var random_num = Math.floor(Math.random() * 4);
$demo.innerHTML = cards[random_num].animal;
//here
$("#demo").hover(function(){
speak();
});
function speak() {
responsiveVoice.speak(cards[random_num].animal, "UK English Male");
}
//end
}
display_text = !display_text;
});
body { font-family: sans-serif; }
.scene {
width: 308px;
height: 446px;
border: 1px solid #CCC;
margin: 40px 0;
perspective: 600px;
}
.card {
width: 100%;
height: 100%;
transition: transform 1s;
transform-style: preserve-3d;
cursor: pointer;
position: relative;
}
.card.is-flipped {
transform: rotateY(180deg);
}
.card__face {
position: absolute;
width: 100%;
height: 100%;
/*line-height: 260px;*/
color: white;
text-align: center;
font-weight: bold;
font-size: 40px;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
.card__face--front {
/*background: red;*/
}
.card__face--back {
background: #009688;
transform: rotateY(180deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="scene scene--card">
<div class="card">
<div class="card__face card__face--front">
<img src="./css/images/pokemon_card.png" width="304" height="442" alt="">
</div>
<div class="card__face card__face--back">
<p id="demo">Back</p>
</div>
</div>
</div>
<p>Click card to flip.</p>
<!-- web speech api -->
<script src="https://code.responsivevoice.org/responsivevoice.js?key=QugTbpmd"></script>
</body>
</html>