问题
The image link I'm using:
echo "<br/><div class='right' id='post" . $id . "'>
<img id='thumb' src='/images/like.png' title='Like it?' alt='Like button'
onClick='likeButton(" . $id . ");'>( " . getLikes($id) . " )</div><br/>";
and the JavaScript is:
function likeButton(id) {
$.ajax({
url: "../../likes/" + id,
type: "post",
data: {
id: id},
success: function(likes) {
$('#post' + id).html(likes);
}});
}
"likes" is the PHP function that adds the click to the db, and it also returns the number (getLikes($id)).
But there's a couple things wrong here. When I click, the image disappears and I'm only left with the number
Instead, I need it to keep showing the image (and the paranthesis around the number) - but change the image src and alt if the PHP function getLikes($id) == "true".
Any takers?
回答1:
Instead of replacing the content of the ENTIRE post, just change the value of the likes:
( " . getLikes($id) . " ) => <span class="likes">( " . getLikes($id) . " )</span>
and
$(`#post${id} .likes`).text(`(${likes})`);
EDIT: Follow-up question:
You asked about preventing clicking more than once. You can add a flag to know they have already clicked.
NOTE: This will only one until they reload the page, it's not a great solution if you really want to block them. Your server should prevent it server-side in PHP instead (e.g. check if they have already like it before incrementing the count by user id + post id).
function likeButton(id) {
if ($('#post' + id).hasClass('already-liked')) {
return;
}
$('#post' + id).addClass('already-liked');
$.ajax({
url: "../../likes/" + id,
type: "post",
data: {
id: id},
success: function(likes) {
$('#post' + id).html(likes);
}});
}
来源:https://stackoverflow.com/questions/62078390/change-img-properties-src-alt-based-on-ajax-success-and-fix-my-ajax