简体   繁体   中英

How to update a number in html via javascript?

After a voter votes, I want to update the count.

<form class="vote-form" action="">
  <div id="{{key}}" class="vote-count">{{votes}}</div>
  <input class="vote-button" type="submit" class="text-button" value="vote+"/>
  <input type="hidden" class="brag" name="brag" value="{{key}}">
  <input type="hidden" class="voter" name="voter" value="{{current_user.fb_id}}">
</form>

<script type="text/javascript">
  $(function() {  
    $('.error').hide();  
    $(".vote-form").submit(function() { 
      var inputs = $(this).find('input:hidden');
      var key = $('input.brag', this).val();
      $.ajax({
        type: "POST",  
        url: "/bean",  
        data: inputs,  
        success: function() {  
          //not sure how to do this, I want to increment {{votes}}
          $('#' + key).innerHTML = "foo"; 
        }  
      });  
      return false;
    });  
  });
</script>
var $div = $('#' + key),
    intValue = parseInt($div.html(), 10);

$div.html(++intValue);

If you want to blindly add 1 to whatever value is in the HTML already:

$('#'+key).html(function(i,old){ return old*1 + 1; });

I would, however, advocate having your server return the correct vote count in response to /bean and using this to update the HTML.

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