2014-12-05 193 views
1

当用户点击取消关注按钮,并成功结束请求,我改变了我的按钮是一个按钮,它仍然在听取消跟踪功能!看到下面的代码jquery点击事件重复

$(document).ready(function() { 
    $("button[data-follow]").on("click",function(){ 

var id = $(this).attr("data-follow"); 
$.ajax({ 
    data: {followid : id } , 
    url:"follow.php", 
    type:"POST", 
    datatype: "json", 
    success: function(data){ 
     alert(data); 
     $(this).css({"background" : "green"}); 



    } 
});}); 





$("button[data-unfollow]").on("click",function(){ 
var there = $(this); 
var id = there.attr("data-unfollow"); 
    $.ajax({ 
    data: {followid : id } , 
    url:"unfollow.php", 
    type:"POST", 
    success: function(data){ 
     alert(data); 
     there.text("follow"); 
     there.attr("data-follow","1234"); 



    } 
}); 



    }); 

     }); 

当我点击按照它应该发送请求跟随url,但它仍然发送到取消关注!

+0

提供您的html也 – 2014-12-05 12:53:53

+0

button取消关注 – 2014-12-05 12:56:20

+0

嗯,通常与委派的事件绑定,你希望父母与参数中的选择器。即$(“#your parent div”)。on(“button [data-follow]”,“click”,function ...等 – 2014-12-05 12:57:01

回答

0

您必须删除 '数据取消关注' 属性在这样的Ajax响应,

$("button[data-unfollow]").on("click",function(){ 
    var there = $(this); 
    var id = there.attr("data-unfollow"); 
    $.ajax({ 
    data: {followid : id } , 
    url:"unfollow.php", 
    type:"POST", 
    success: function(data){ 
     alert(data); 
     there.text("follow"); 
     there.attr("data-follow","1234"); 
     there.removeAttr('data-unfollow'); // try removing the data-unfollow attribute 
    } 
}); 

:::::::::::::::::::::: ::::::编辑:::::::::::::::::::::::::::::::::::::::::

将您的第一行JS代码更改为thism其工作......

$(document).on("click","button[data-follow]",function(){ 

$(document).on("click","button[data-unfollow]",function(){ 

并且不要忘记使用.removeAttr()。

+0

这不会解除以前的点击处理程序 – 2014-12-05 12:59:25

+0

嗯,不工作以及:? – 2014-12-05 13:02:43

+0

请检查我已编辑的答案现在... – Pankaj 2014-12-05 13:11:33

0

使用.prop API添加的属性和.removeProp API来删除一个属性

$(function(){ 

     $('button').on('click',function(e){ 
      $(this).removeProp('data-unfollow'); 
      $(this).prop('data-follow','Ok'); 
      alert($(this).prop('data-follow')); 
     }); 

    }); 

希望它可以帮助...

0

通常与委托事件绑定你想选择的父参数。

例如

$("#your parent div").on("click", "button[data-follow]", function() 
{ function contents here }); 

这是因为家长需要注意DOM的变化。