简体   繁体   中英

Replacing a div that is called by jQuery onclick

I have a list object and each contains an upvote div that is called onclick by my jQuery (I essentially flip the vote button in each div and asynchronously change the vote for that div via Ajax).

All object divs are contained within row.replace which I use to sort the objects asynchronously. The thing is that once I click on the sorter and sort the content of the .row.replace div, the upvote divs in the sorted list of objects stop getting called onclick ie. I can upvote and remove my upvote before sorting with jQuery+ajax, once the sort is applied and the contents of the div are replaced, my upvote button stops working.

Here is the jQuery:

$(document).ready(function () {
  $('.sorter').click(function () {
    $('.row.replace').empty();
    $('.row.replace').append("<br><br><br><br><p align='center'><img id='theImg' src='/media/loading1.gif'/></p><br><br><br><br><br><br><br><br>");
    var sort = $(this).attr("name");
    $.ajax({
      type: "POST",
      url: "/filter_home/" + "Lunch" + "/" + "TrendingNow" + "/",
      data: {
        'name': 'me',
        'csrfmiddlewaretoken': '{{csrf_token}}'
      },
      dataType: "json",
      success: function (json) {
        //loop through json object
        //alert("yoo");
        $('.row.replace').empty();
        for (var i = 0; i < json.length; i++) {
          $('.row.replace').append("<div class='showroom-item span3'> <div class='thumbnail'> <img class='food_pic' src='/media/" + json[i].fields.image + "' alt='Portfolio Image'> <div class='span3c'> <a><b>" + json[i].fields.name + "</b> </a> </div> <div class='span3d'> posted by <a><b>" + json[i].fields.creator.username + "</b></a> </div> <div class='span3c'> <div class='btn-group'> <div class='flip flip" + json[i].pk + "'> <div class='card'> {% if 0 %} <div class='face front'> <button type='button' class='btn btn-grove-one upvote' id='upvote' name='" + json[i].pk + "'>Upvoted <i class='glyphicons thumbs_up'><i></i></i><i class='vote-count" + json[i].pk + "'>" + json[i].fields.other_votes + "</i></a></button> </div> <div class='face back'> <button type='button' class='btn btn-grove-two upvote' id='upvote' name='" + json[i].pk + "'>Upvote <i class='glyphicons thumbs_up'><i></i></i><i class='vote-count" + json[i].pk + "'>" + json[i].fields.other_votes + " </i></a></button> </div> {% else %} <div class='face front'> <button type='button' class='btn btn-grove-two upvote' id='upvote' name='" + json[i].pk + "'>Upvote <i class='glyphicons thumbs_up'><i></i></i><i class='vote-count" + json[i].pk + "'>" + json[i].fields.other_votes + " </i></a></button> </div> <div class='face back'> <button type='button' class='btn btn-grove-one upvote' id='upvote' name='" + json[i].pk + "'>Upvoted <i class='glyphicons thumbs_up'><i></i></i><i class='vote-count" + json[i].pk + "'>" + json[i].fields.other_votes + "</i></a></button> </div> {% endif %} </div> </div> </div> <div class='btn-group'> <button type='button' class='btn btn-grove-two'><i class='glyphicons comments'><i></i></i>" + json[i].fields.comment_count + "</a></button> </div> </div> </div> </div>");
        }
        //json[i].fields.name
      },
      error: function (xhr, errmsg, err) {
        alert("oops, something went wrong! Please try again.");
      }
    });
    return false;
  });
  $('.upvote').click(function () {
    var x = $(this).attr("name");
    $.ajax({
      type: "POST",
      url: "/upvote/" + x + "/",
      data: {
        'name': 'me',
        'csrfmiddlewaretoken': '{{csrf_token}}'
      },
      dataType: "json",
      success: function (json) {
        var y = "vote-count" + x;;
        $('i[class= "' + y + '"]').text(json.vote_count);
        //flip button
        $('.flip' + x).find('.card').toggleClass('flipped');
      },
      error: function (xhr, errmsg, err) {
        alert("oops, something went wrong! Please try again.");
      }
    });
    return false;
  });
});

The click event handler only binds to elements that exist in the DOM when the function is actually called. You need to use a delegated on() event listener to bind to future elements as well. So for your code:

$('.upvote').click(function(){

change to:

$("body").on("click", '.upvote', function(event){

Should catch future click events. I'm using "body" as the outer selector because I don't know what your HTML looks like, but it's best to "outer-bind" to the nearest ancestor to the '.upvote elements (so if they are all contained in a ul` with id "vote-list" bind to that instead of "body").

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