2016-05-13 39 views
0

我無法弄清楚如何使用Jquery重置按鈕的內容。目前,當按下.button時,我會得到一個隨機字母,它們都是三個div。然而,迄今爲止這麼好,再次按下時,第一個字母保持不變,另一個字母被添加。我需要第一個結果消失並顯示一封新信。這裏是我的代碼..使用Jquery重置div內容

$(document).ready(function() { 
    $('.button').click(function() { 
    var itemList = new Array("A", "B", "C", "D", "E"); 
    var randomItem = Math.floor(Math.random() * (itemList.length)); 
    $('.random1').append(itemList[randomItem]); 
    var randomItem = Math.floor(Math.random() * (itemList.length)); 
    $('.random2').append(itemList[randomItem]); 
    var randomItem = Math.floor(Math.random() * (itemList.length)); 
    $('.random3').append(itemList[randomItem]); 
    }); 
$('.reset').on('click', function(){ 
    $(".random1").trigger("reset"); 
    }); 
}); 

回答

1

這是因爲你使用的是.append(val)方法,這將在元素的末尾添加新數據舊數據。如果您想要清除元素中的舊數據,請使用.text(val)方法。

例如,你會改變這一行:

$('.random1').append(itemList[randomItem]); 

要:

$('.random1').text(itemList[randomItem]); 
0

斯賓塞給你整理,但我還要提到的是,除了使用.text()而不是.append()解決您的主問題,您還可以使用.each()這樣簡化代碼:

$(function() { 
 
    $('.button').click(function() { 
 
    var itemList = ["A", "B", "C", "D", "E"]; 
 
    $('.random').each(function(){ 
 
     $(this).text(Math.floor(Math.random() * (itemList.length))); 
 
    }); 
 
    }); 
 
$('.reset').click(function(){ 
 
    $(".random").text(""); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button class="button">Get random</button><button class="reset">reset</button><br><br> 
 
<div class="random"></div><br> 
 
<div class="random"></div><br> 
 
<div class="random"></div><br> 
 
<div class="random"></div><br>