2017-02-13 90 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