在jQuery中,您可以使用相對定位來選擇感興趣的項目。因此,例如,如果每個項目後面跟着一個收藏夾按鈕,則可以從單擊的項目遍歷DOM以查找相關項目。然後,您可以通過AJAX將其發回,以根據需要存儲更新元素以反映更新狀態。
HTML(假設你使用的造型,以顯示圖標,最喜歡的狀態)
<span class="normal" data-location="A">Location A</span> <span class="icon-favorite"></span>
JS
$('.favorite').click(function() {
var data = [],
newClass = 'favorite',
oldClass = 'normal',
$this = $(this),
$location = $(this).prev('span');
// if already favorited, reverse the sense of classes
// being applied
if ($location.hasClass('favorite')) {
newClass = 'normal';
oldClass = 'favorite';
}
data['location'] = $location.attr('data-location');
$.post('/toggle_favorite', data, function(result) {
if (result.Success) {
$location.removeClass(oldClass).addClass(newClass);
$this.removeClass('icon-'+newClass).addClass('icon-'+oldClass);
}
else {
alert('could not mark as favorite');
}
},'json');
});
http://stackoverflow.com/questions/10033215/add-to-favorites-按鍵 – webmaniacgr