gpt4 book ai didi

javascript - 使用 jQuery 使 div 值在使用 $(this) 的地方上升或下降

转载 作者:行者123 更新时间:2023-11-30 12:58:46 26 4
gpt4 key购买 nike

我有一个非常好的脚本,允许用户“点赞”评论。该脚本使用 jQuery 使“大拇指”图像在用户单击时变为绿色。用户还可以通过再次单击图像来“取消点赞”评论,图像将从绿色变为白色。最后,有一个小 div 显示对特定评论“点赞”的人数。

这就是我的问题所在。截至目前,当用户单击或取消单击“点赞”时,带有评论点赞总数的小 div 不会立即刷新。只有当用户刷新页面时,数字才会改变。如果用户点赞评论(即使图像变为绿色),我希望 div 自动增加 1 个整数;如果用户取消点赞(即,将图像从绿色变为白色)。

总点赞数的“小div”是这样调用的(完整用法见第二段代码):

<div class='upvote_count'>$total_upvotes</div>

我遇到了麻烦,因为我的 jQuery 使用“$(this)”并且我不知道如何引用另一个元素...关于如何实现这一点的任何想法都会非常有帮助。

我的 JQUERY:

<script>
$(document).ready(function() {

$('.thumb a').on('click', function(e) {
e.preventDefault();
var $img = $(this).find('img');
var $idshow = $(this).attr("id");

if($img.hasClass('thumbsUp')) {
$img.removeClass('thumbsUp');
} else {
$img.addClass('thumbsUp');
}

$img.attr('src', function(_,s) {
return s.indexOf('thumbs_up_green') > -1 ? '../images/thumbs_up.png'
: '../images/thumbs_up_green.png'
});

$.get("thumb_up_tip.php?tip_id=" + $idshow + "&x=" + "<?php echo "1"; ?>")

if($img.hasClass('thumbsUp')) {
alert("up");
//THIS IS WHERE I WANT <div class='upvote_count'>$total_upvotes</div> TO GO UP 1
} else {
alert("down");
//THIS IS WHERE I WANT <div class='upvote_count'>$total_upvotes</div> TO GO DOWN 1
}

});

});
</script>

这是我的 HTML:

echo "
<table width='100%' class='box'>
<tr>
<td><span class='item'>$p[first_name] </span><span class='price'>
($tip_city_store$p[date_time])</span></td>
<td align='center' valign='top'><div class='upvote_count'>$total_upvotes</div></td>
</tr>
<tr>
<td width='87%' valign='top'>
<span class='desc'>$p[tip]</span>
</td>
<td width='13%' align='center' valign='top'>
<span class='thumb'>
<a href='#' id = '$p[tip_id]' onClick='thumbTip(this)'>";

if ($upvote_count=="0")
{
echo "<img src='../images/thumbs_up.png' width='21' scalefit='1'>";
}

if ($upvote_count=="1")
{
echo "<img src='../images/thumbs_up_green.png' width='21' scalefit='1'
class='thumbsUp'>";
}

echo "</a>
</span>
</td>
</tr
</table>";

最佳答案

首先,您可以结合使用 closestfind 来获取与单击按钮相关的 .upvote_count 元素。

其次,您的逻辑有点缺陷,需要 DRYing up。试试这个:

$('.thumb a').on('click', function(e) {
e.preventDefault();
var $img = $(this).find('img');
var idshow = this.id;
var $counter = $(this).closest('table').find('.upvote_count');

if ($img.hasClass('thumbsUp')) {
$img
.removeClass('thumbsUp')
.attr('src', '../images/thumbs_up.png');
$counter.text(parseInt($counter.text(), 10) - 1);
}
else {
$img
.addClass('thumbsUp')
.attr('src', '../images/thumbs_up_green.png');
$counter.text(parseInt($counter.text(), 10) + 1);
}

$.get("thumb_up_tip.php?tip_id=" + idshow + "&x=<?php echo "1"; ?>");
});

关于javascript - 使用 jQuery 使 div 值在使用 $(this) 的地方上升或下降,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18099493/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com