假设我有一个单词数组
JS
card-image-container{
background: url('https://placeimg.com/640/480/animals') 50% no-repeat;
background-size: cover;
}
我需要在单击句子的中间单词时触发功能,以获得不同的随机匹配
HTML
var fruit = [banana, apple, watermelon, mango];
function loadFruit() {
var randomFruit = fruit[Math.floor(Math.random() * fruit.length)];
$('.divLoadFruit').parent('div').html(randomFruit);
};
当你点击其中一个链接时,它会触发相同的功能(显然),但在那个空间中获得相同的水果。有没有办法让它随机而不重复?
答案 0 :(得分:1)
考虑到您单击锚标记并获得随机水果,以下代码将起作用。
var fruit = ['banana', 'apple', 'watermelon', 'mango'];
function loadFruit(id) {
var randomFruit = fruit[Math.floor(Math.random() * fruit.length)];
document.getElementById(id).innerHTML = randomFruit;
};
You need to eat <a id='just_some_fruit' href='javascript: loadFruit("just_some_fruit");'>just_some_fruit</a>: it is good for your health.
My son doesn´t like <a id='another_fruit_here' href='javascript: loadFruit("another_fruit_here");'>another_fruit_here</a>.
答案 1 :(得分:1)
这是一种使用jquery的方法。
var fruit = ["banana", "apple", "watermelon", "mango"];
function loadFruit(caller) {
var randomFruit = fruit[Math.floor(Math.random() * fruit.length)];
$(caller).html(randomFruit);
};
$('a').click(function() {
loadFruit(this);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div>
"You need to eat <a href='#'>just_some_fruit</a>: it is good for your health." "My son doesn´t like <a href='#'>another_fruit_here</a>."
</div>
&#13;
希望有所帮助!