2014-12-15 3 views
1

나는 isbn 검색 input과 제출 button을 가지고 있습니다. 양식 제출시 결과는 양식 아래의 div에 표시되며 정상적으로 작동합니다.제출시 div 내용 재설정

제 문제는 제출을 반복해서 눌러 여러 div가 차례로 나타날 수 있다는 것입니다.

제출을 누를 때마다 div의 내용을 어떻게 바꿀 수 있습니까?

내 코드까지;

$("#form").submit(function() { 

    var isbn = $('#isbn_search').val(); 
    var url='https://www.googleapis.com/books/v1/volumes?q=isbn:'+isbn; 
    event.preventDefault(); 
    $.getJSON(url,function(data){ 
      $.each(data.items, function(entryIndex, entry){     
       var html = '<div class="result">'; 
       html += '<h3>' + (entry.volumeInfo.title)+ '</h3>'; 
       $(html).hide().appendTo("#result").fadeIn(1000); 
      }); 
    }); 

});

<form id="form" method="post" action=""> 
    <label>ISBN: </label> 
    <input type="text" id="isbn_search" name="isbn_search" /> 

    <input type="submit" value='Search Google Books' /> 
</form> 

<div id="result"></div> 

답변

2

새 데이터를 추가하기 전에 #result의 html을 재설정하면됩니다. 이와 같은 :

... 
$.getJSON(url,function(data){ 
    $('#result').html(''); 
    $.each(data.items, function(entryIndex, entry){ 
... 
1

간단히 같은 :

$("#form").submit(function() { 

    var isbn = $('#isbn_search').val(); 
    var url='https://www.googleapis.com/books/v1/volumes?q=isbn:'+isbn; 
    event.preventDefault(); 
    $.getJSON(url,function(data){ 
      $.each(data.items, function(entryIndex, entry){  
       $("#result").empty(); //reset result div content 
       var html = '<div class="result">'; 
       html += '<h3>' + (entry.volumeInfo.title)+ '</h3>'; 
       $(html).hide().appendTo("#result").fadeIn(1000); 
      }); 
    }); 
});