jQuery:没有刷新的POST数据

时间:2014-03-29 19:45:43

标签: javascript jquery css ajax

链接在页脚中,问题是:onclick,页面跳转到地址栏中带#的标题,有没有办法留在页脚?

这是我的代码

<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','');
    });
    }
});

由于

4 个答案:

答案 0 :(得分: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 :(得分: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','');
    });
    }
});

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

答案 2 :(得分: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','');
    });
    }
});

答案 3 :(得分:1)

内部点击使用

event.preventDefault();