斗士狗 2012-07-29 11:36 采纳率: 0%
浏览 112

jQuery ajax addClass问题

First sorry im a big beginner and just experimenting, and I made a similar wall like facebook with oembed.

And would like to add a like, and dislike button too.

I started with the like button, it works, likes, and unlikes too, and the cookie saves the class value perfectly.

My problems is the ajax call, so actually when I click on the like button it overwrites all anchors href val and adds a class to all not on what click.

here is my code

jquery

var cookieLike = "like_"
$('a.like').each(function(){
    var id = $(this).attr('href'), cookieLiked = cookieLike + id;

    switch($.cookies.get(cookieLiked) ) {
        case "unliked":
            $(this).removeClass('btn-success');
        break;
        case "liked":
            $(this).addClass('btn-success');
        break;
    }
}).on('click', function(e){
    e.preventDefault()
    var likeId = $(this).attr('href');
    $.ajax({
        url: "<?php echo base_url(); ?>stream/like/" + likeId ,
        type: "post",
        data: likeId,
        dataType: "json",
        success: function(like)
        {

            if(like.likeStatus == "unliked") {
                $('a.like').attr('href', likeId).removeClass('btn-success');
                $.cookies.set(cookieLike + likeId, 'unliked');

            }else if(like.likeStatus == "liked") {
                $('a.like').attr('href', likeId).addClass('btn-success');
                $.cookies.set(cookieLike + likeId, 'liked');

            }

        }
    });

});

html

<div class="stream-bottom">
    <a href="#" class=" btn btn-mini comment">Komment</a>
    <div class="pull-right like-options">
        <a href="<?php echo $sp->sid; ?>" class=" btn btn-mini like"><i class="icon-thumbs-up" title="tetszik"></i> </a>
        <a href="<?php echo $sp->sid; ?>" class=" btn btn-mini dislike"><i class="icon-thumbs-down" title="nem tetszik"></i></a>
    </div>
</div>

could please someone point out what i am missing?

  • 写回答

3条回答 默认 最新

  • 笑故挽风 2012-07-29 11:40
    关注

    Bind the target element (the clicked link) and reference it in the success callback

    In the .on('click') callback

    var $link = $(this);
    

    In the success callback use

    $(this).attr('href', likeId)
    

    instead of

    $('a.like').attr('href', likeId)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计