douchao1864 2015-12-29 12:42
浏览 43
已采纳

JQuery attr总是返回相同的值

Guys i have post list where each post have own ID. I want with jquery to get that id from custom attribute. Problem is when i try to debug i get all time the some value.

This is html table that i list from database with PHP. Each post have specific ID.

Name      |    id 
-------------------
Post 1    |   188
Post 2    |   189
Post 3    |   190

<i id="like" class="glyphicon glyphicon-heart" data-id="<?=$post->post_id;?>"></i> Like

So when i try to get value from data-id script all time return 188 number. When click on Post 1, post 2, post 3 all time value is 188!!! Whay ?

Here is JQuery:

isPostLiked: function() {
    var isLiked = false;
    var likeText = $("#like");
    var itemId = likeText.attr("data-id");

    // debug 
    Post.postLikeBtn.click(function() {
      console.log(itemId);
    });

    //$.ajax({
    //    type: "post",
    //    url: baseurl + "/like/isLikedAjaxAction/"
    //});

    if (isLiked == true) {
      likeText.css("color", "red");
    }
},
  • 写回答

2条回答 默认 最新

  • duangekui7451 2015-12-29 12:47
    关注

    It seems you are generating HTML in a loop. Remember Identifiers in HTML must be unique, you can use CSS class then Class Selector (“.class”) can be used. Modify you HTML as

    <i class="like glyphicon glyphicon-heart" data-id="<?=$post->post_id;?>"></i> Like
    

    Change click handlers and fetch ids using the current element context i.e. this

    $('.like').click(function(){
        var id= $(this).data('id');
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 YOLOv8obb获取边框坐标时报错AttributeError: 'NoneType' object has no attribute 'xywhr'
  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开