2017-02-13 105 views
0

我有一個ajax函數,它有兩個結果,具體取決於所單擊鏈接的類。在jQuery中更改鏈接狀態

我不想重新加載整個頁面鏈接被點擊的時候,所以我用:

這除了儘可能jQuery是所有有關的作品,它看起來好像它仍然有原班,所以再次點擊它,只是反思「短名單添加」腳本而不是「短名單刪除」腳本。

<button data-propref="261" id="prop-261" class="btn-round btn-favorite shortlist-remove"><span class="icon-hearth"></span></button>

// remove property from shortlist 
jQuery('.shortlist-remove').on('click',function() { 

    var propref = jQuery(this).data('propref'); 

    jQuery.ajax({ 
     url : ajax_object.ajax_url, 
     type : 'post', 
     data : { 
      action : 'shortlist_rem', 
      propref : propref 
     }, 
     success : function(response) { 
      jQuery('.personal-nav').load(document.URL + ' .personal-nav'); 
      jQuery('#prop-' + propref).removeClass('shortlist-remove').addClass('shortlist-add'); 
     } 
    }); 
}); 
+4

不明確的問題是什麼類 - 你可以改一下?你是否試圖移除綁定到'.click()'的事件並修改類? – G0dsquad

+3

請你也可以創建一個[MCVE] – Pete

+0

G0dsquad,是的,我認爲這就是我想要做的! – Badger

回答

1

使用的是保持所有的時間作爲你的主要選擇一類。

然後使用基於其他2個類的條件來改變行爲...在這種情況下切換action

然後切換的成功處理程序

$('.btn-favorite').on('click', function(e) { 
    var $btn = $(this), 
    isRemove = $btn.hasClass('shortlist-remove'), 
    propref = jQuery(this).data('propref'); 

    jQuery.ajax({ 
    .... 
    data: { 
     // action determined by classes 
     action: isRemove ? 'shortlist_rem' : 'shortlist_add', 
     propref: propref 
    }, 
    success: function(response) { 

     // toggle the classes now that ajax successful 
     $btn.toggleClass('shortlist-remove shortlist-add'); 

     // other stuff 
    } 
    }); 

}) 
+0

這是做的伎倆,非常感謝。 – Badger