2010-03-11 4 views
4

작은 이미지를 사용하여 테이블의 여러 행에서 즐겨 찾기로 레코드를 표시하는 프로젝트가 있습니다. 데이터는 DB에서 가져오고 이미지는 해당 항목이 즐겨 찾기인지 여부에 따라 달라집니다. 즐겨 찾기에 대한 하나의 이미지, 즐겨 찾기가 아닌 다른 이미지. 사용자가 이미지를 전환하여 좋아하는 이미지로 만들 수 있기를 바랍니다. 내 코드는 다음과 같습니다.알 수없는 초기 상태의 jQuery 토글()

$(function() { 
    $('.FavoriteToggle').toggle(
     function() { 
     $(this).find("img").attr({src:"../../images/icons/favorite.png"}); 
     var ListText = $(this).find('.FavoriteToggleIcon').attr("title"); 
     var ListID = ListText.match(/\d+/); 
     $.ajax({ 
      url: "include/AJAX.inc.php",  
      type: "GET", 
      data: "action=favorite&ItemType=0&ItemID=" + ListID,   
      success: function() {}  
     }); 
     }, 
     function() { 
     $(this).find("img").attr({src:"../../images/icons/favorite_not.png"}); 
     var ListText = $(this).find('.FavoriteToggleIcon').attr("title"); 
     var ListID = ListText.match(/\d+/); 
     $.ajax({ 
      url: "include/AJAX.inc.php",  
      type: "GET", 
      data: "action=favorite&ItemType=0&ItemID=" + ListID,   
      success: function() {}  
     }); 
     } 
    ); 
}); 

초기 상태가 좋지 않은 경우 위대한 작품입니다. 처음에 좋아하는 이미지를 변경하려면 두 번 클릭해야합니다. 이로 인해 AJAX가 두 번 발사되고 이미지가 응답하기 전에 AJAX가 즐겨 찾기가 아닌 즐겨 찾기가됩니다. 사용자는 이미지가 변경 되었기 때문에 그가 좋아하는 것으로 생각하지만 실제로는 그렇지 않습니다. 누구 한테 도움을 줘?

+0

@ 제이슨 : 어떤 시점에서 주어진 답변 중 하나를 평가/코멘트에 사용 하시겠습니까? – Tomalak

답변

0

이 당신을 위해 올바른 방향으로가는 경우 몰라요 -하지만 난 보통 토글 기능으로 사용할 - 그리고 몇 가지 추가 PHP와 내가 하나 또는 다른 초기 상태로 조정도 할 수 있습니다

<style type="text/css"> 
<!-- 
.mybox_edit { 
display: none; 
} 
--> 

</style> 

<script language="JavaScript" type="text/JavaScript"> 
<!-- 

function toggleBox(box_id) { 
var box_edit = document.getElementById(box_id + "_edit"); 
var box_show = document.getElementById(box_id + "_show"); 

// is it hidden? 
if (box_show.style.display == 'none') { 
box_show.style.display = 'block'; 
box_edit.style.display = 'none'; 
} else { 
box_show.style.display = 'none'; 
box_edit.style.display = 'block'; 
} 
} 
//--> 
</script> 
+0

이것이 작동 할 수 있지만 jQuery는 아닙니다. jQuery 라이브러리를로드 중이므로 그 오버 헤드를 최대한 활용하고 싶습니다. –

1

state를 정의하는 favoriteToggle에 클래스를 추가합니다. 이 아이콘을 사용하여 이미지를 바꾸지 말고 아이콘에 CSS를 정의하십시오. 그런 다음 즐겨 찾는 토글의 상태를 쉽게 파악할 수 있습니다. 당신은 당신이 원하는 경우 단지와 이미지를 변경 그럼 당신은 더 많은 일을 할 수 있도록 상태를 정의하는 클래스를 가진 얻을 이렇게

.FavoriteToggle .icon{ 
    background: url("../../images/icons/favorite_not.png"); 
} 
.FavoriteToggle.isFavorite .icon{ 
    background: url("../../images/icons/favorite.png"); 
} 

을하고 :

$(function() { 
$('.FavoriteToggle').click(function(){ 
    var $this = $(this); 
    var id = $this.find('.FavoriteToggleIcon').attr("title").match(/\d+/); 
    if ($this.hasClass('isFavorite')){ 
     $this.removeClass('isFavorite'); 
    } else { 
     $this.addClass('isFavorite'); 
    } 
    $.ajax({ 
     url: "include/AJAX.inc.php",  
     type: "GET", 
     data: "action=favorite&ItemType=0&ItemID=" + id,   
     success: function() {}  
    }); 
}) 
}); 

당신의 CSS에 추가 항상 더러운 javascript에서 이미지 경로를 정의하도록합니다.

0
$(function() { 
    // toggle on click 
    $('.FavoriteToggle').click (function() { 
    // prevent duplicate AJAX request with a "loading" flag 
    if (!this.isLoading) { 
     var $img = $(this).find("img"); 
     var ListID = $(this).find('.FavoriteToggleIcon').attr("title").match(/\d+/); 

     // flag that we are currently loading something 
     this.isLoading = true;  

     // determine the action from the current state of the img 
     if ($img.attr("src").indexOf("favorite.png") > -1) 
     var actionVerb = "unFavorite"; 
     else 
     var actionVerb = "mkFavorite"; 

     $.ajax({ 
     url: "include/AJAX.inc.php",  
     type: "GET", 
     data: {action: actionVerb, ItemType: 0, ItemID: ListID }, 
     success: function($i) { 
      return function() { 
      // change image on success only 
      if ($i.attr("src").indexOf("favorite.png") > -1) { 
       $i.attr("src", "../../images/icons/favorite_not.png"; 
      else 
       $i.attr("src", "../../images/icons/favorite.png"; 
      }; 
     }($img), 
     error: function(xhr, textStatus, errorThrown) { 
      // make some note of the error 
      alert(textStatus); 
     } 
     complete: function(p) { 
      return function(xhr, textStatus) { 
      // set loading flag to false when done 
      p.isLoading = false; 
      }; 
     }(this) 
     }); 
    } 
    }); 
}); 

테스트되지 않았지만 아이디어를 얻어야합니다.

전체 if ($img.attr("src").indexOf("favorite.png") 물건

은 훨씬 더 쉽게 <img>favorite CSS 클래스를 추가하여 수행 할 수 있습니다. 예를 들면, 주요 기능에 다음 success 콜백에서

var actionVerb = $img.is(".favorite") ? "unFavorite" : "mkFavorite"; 

과 :

if ($i.is(".favorite")) 
    $i.attr("src", "../../images/icons/favorite_not.png"; 
else 
    $i.attr("src", "../../images/icons/favorite.png"; 

// now toggle the CSS class 
$i.toggleClass("favorite") 
0

음, 여기 내가 위에서 PetersenDidit's post의 단순화 된 버전으로 결국 것입니다.

$('.FavoriteToggle').click(function() { 
    var id = $(this).attr("title").match(/\d+/); 
    if ($(this).hasClass('isFavorite')) { 
     $(this).removeClass('isFavorite'); 
    } else { 
     $(this).addClass('isFavorite'); 
    } 
    $.ajax({ 
     url: "include/AJAX.inc.php", 
     type: "GET", 
     data: "action=favorite&ItemType=0&ItemID=" + id, 
     success: function() { 
     } 
    }); 
});