I am creating a 'favorites' style system for a property webiste where users can save a property to be viewed later. The system works using Jquery so the page doesn't have to refresh. The details page of 开发者_如何转开发a property contains a 'add to favorites button' and this works fine:
$("#addFavorites").click(function() {
var locationID = $("#locationID").val();
But how would I code this when all of the properties are listed together on one page, each 'add to favorites' button would have to use a unique id or something but not sure how to approach this.
Well the most precise way would be a default HTML-Formular. I'll make it a short one:
<form ...>
<label for="fav1">Fav1</label>
<input type="checkbox" name="favorites[]" id="fav1" value="1" />
<label for="fav2">Fav2</label>
<input type="checkbox" name="favorites[]" id="fav2" value="2" />
<submit>
</form>
Now that's the ugly form, you can make this beautiful with CSS. With jQuery you now always submit the form when the user checks any of the checkboxes, like:
$('input[type=checkbox]').change(//do ajax submit);
In the AJAX File you simply read the array:
foreach($_POST['favorites'] as $fav) {
addFavToUser($fav, $user);
}
This is like simply explained to give you an idea, not the whole "clean" solution. But i hope this helps you - if it does, i always appreciate the vote for it ;)
Each of your 'favorites' would need a unique id
... ...
Then.. $('.favorite').click(function(){
$(this).whateveryouwanttodo();
});
$(this) will contain the clicked anchor tag. from that you can get the id, and call your ajax post or whatever you want to do with it.
In jQuery you can use relative positioning to select the item of interest. So, for example, if each item was followed by a favorite button, you can traverse the DOM from the clicked item to find the related item. You can then post this back via AJAX to store it an update the element as needed to reflect the updated status.
HTML (assumes you use styling to show the icon and favorite status)
<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');
});
精彩评论