dtr32787 2017-08-18 14:22
浏览 4
已采纳

更改类jquery

Good evening, I can not run this code: in practice, you add the new class but you do not delete the old one. It's a simple system of like and dislike

$query2 = mysql_query("SELECT * FROM totlike WHERE id_user_like = $id_user AND id_post_like = ". $risultato['id'].""); 
if (mysql_num_rows($query2) == 1) {
  $like = '<i class="glyphicon glyphicon-heart" id="'. $risultato['id'] .'"></i>';
} else {
  $like = '<i class="glyphicon glyphicon-heart-empty" id="'. $risultato['id'] .'"></i>';
}
var elem = $('#' + id_post).attr('class');
if (elem == "glyphicon glyphicon-heart") {
  $('#' + id_post).removeClass('glyphicon glyphicon-heart').addClass('glyphicon glyphicon-heart-empty');
  } else {
    $('#' + id_post).removeClass('glyphicon glyphicon-heart-empty').addClass('glyphicon glyphicon-heart');
}
  • 写回答

1条回答 默认 最新

  • dsa45132 2017-08-18 14:41
    关注

    I have cleaned up your code a little, but generally it seems fine. I am not sure if this will help but the snippet below shows it working fine.

    function toggleHeart(id_post) {
        var element = $('#' + id_post);
        if (element.hasClass("glyphicon-heart")) {
            element.removeClass('glyphicon-heart');
            element.addClass('glyphicon-heart-empty');
          } else {
            element.removeClass('glyphicon-heart-empty');
            element.addClass('glyphicon-heart');
        }
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css" rel="stylesheet">
    
    <p>Click on the button or heart to toggle</p>
    <i class="glyphicon glyphicon-heart" id="1" onClick="toggleHeart(1)">1</i>
    <button onClick="toggleHeart(1)">Toggle</button>
    <br />
    <i class="glyphicon glyphicon-heart-empty" id="2" onClick="toggleHeart(2)">2</i>
    <button onClick="toggleHeart(2)">Toggle</button>

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分