2014-03-29 28 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();