2014-03-29 30 views
0

链接在页脚中,问题是:onclick,页面跳转到地址栏中的#标题,有没有办法留在页脚?jQuery:POST数据无刷新

这里是我的代码

<a href="#" class="clickIn" id="1" attrIn="Like"><span style="color: #33A13D"><i class="fa fa-hand-o-up"></i></span></a> 

$(document).on('click', '.clickIn', function(){ 
    var $this = $(this); 
    var liCount = $('#liCount'); 
    if($(this).attr('attrIn')=='Like'){ 
     $.post('page.php',{i:$(this).attr('id'),action:'like'},function(){ 
     $this.html('done'); 
     $this.attr('attrIn',''); 
    }); 
    } 
}); 

感谢

回答

1

使用event.preventDefault():

$(document).on('click', '.clickIn', function(e){ 
    e.preventDefault(); 
    var $this = $(this); 
    var liCount = $('#liCount'); 
    if($(this).attr('attrIn')=='Like'){ 
     $.post('page.php',{i:$(this).attr('id'),action:'like'},function(){ 
     $this.html('done'); 
     $this.attr('attrIn',''); 
    }); 
    } 
}); 

该取消特定元素浏览器的默认操作。检查参考:http://api.jquery.com/event.preventDefault/

1

呦需要修改您添加的处理程序e.preventDefault()和e.stopPropagation():

$(document).on('click', '.clickIn', function(e){ 
    e.preventDefault(); 
    e.stopPropagation(); 
    var $this = $(this); 
    var liCount = $('#liCount'); 
    if($(this).attr('attrIn')=='Like'){ 
     $.post('page.php',{i:$(this).attr('id'),action:'like'},function(){ 
     $this.html('done'); 
     $this.attr('attrIn',''); 
    }); 
    } 
}); 

这将防止默认操作的链接(遵循 “#” 链接)并停止点击事件的传播(冒泡)。

1

您可以通过调用事件对象的preventDefault方法来防止触发事件的默认行为。即:

点击使用
$(document).on('click', '.clickIn', function(event){ 
    var $this = $(this); 
    var liCount = $('#liCount'); 

    // Do this: 
    event.preventDefault(); 

    if($(this).attr('attrIn')=='Like'){ 
     $.post('page.php',{i:$(this).attr('id'),action:'like'},function(){ 
     $this.html('done'); 
     $this.attr('attrIn',''); 
    }); 
    } 
}); 
1

event.preventDefault();