斗士狗 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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog