简体   繁体   中英

Handling of click events in jQuery(For Like and Unlike button)

I am trying to create a Like-Unlike system using AJAX and jQuery. The "like" event seems to work properly, but when I want to "unlike" the event is not responding. Any suggestions to solve this problem is appreciated.

$(document).ready(function() {
    $(".like").click(function() { //this part is working
        var item_id = $(this).attr("id");
        var dataString = 'item_id=' + item_id;
        $('a#' + item_id).removeClass('like');
        $('a#' + item_id).html('<img src="images/loader.gif" class="loading" />');
        $.ajax({
            type: "POST",
            url: "ajax.php",
            data: dataString,
            cache: false,
            success: function(data) {
                if (data == 0) {
                    alert('you have liked this quote before');
                } else {
                    $('a#' + item_id).addClass('liked');
                    $('a#' + item_id).html(data);
                }
            }
        });

    });

    $(".liked").click(function() { //this part is not working
        var item_id = $(this).attr("id");
        console.log(item_id);
        var dataString = 'item_id=' + item_id;
        $('a#' + item_id).removeClass('liked');

        $('a#' + item_id).html('<img src="images/loader.gif" class="loading" />');
        $.ajax({
            type: "POST",
            url: "ajax.php",
            data: dataString,
            cache: false,
            success: function(data) {
                if (data == 0) {
                    alert('you have liked this quote before');
                } else {
                    $('a#' + item_id).addClass('like');
                    $('a#' + item_id).html(data);
                }
            }
        });

    });
});

$(".like") and $(".liked") are retrieved when the document is ready but don't get updated when you add/remove classes from an element.

If you assign a more generic class the vote elements like 'like-toggle' you would be able to do the following:

 $(document).ready(function() { $('.like-toggle').click(function(event) { if ($(event.target).hasClass('like') { // Call your unlike code, replace like with liked. } else { // Call your like code, replace liked with like. } }); }); 

This will work because the like-toggle class never gets removed from the elements and thus the elements which are present when the document is ready will keep functioning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM