How to disable button after its been clicked using

2019-06-05 11:07发布

问题:

How to disable each button after its been clicked, also how to increment like counter through jQuery?

I am building a 'like' button for each comment and posting data using jQuery to PostsController. I am passing the Id value, @item.Id, for each item in the loop and handling the Id through below jQuery code.

@foreach (var item in Model.PostComments)
{ 
    <a id="@item.Id" href="#" class="btn-sm btn-success btn-like"><span class="glyphicon glyphicon-thumbs-up"></span></a>
                    <span id="commentcounter">@Model.CommentMetrics.Where(a => a.PostCommentId == item.Id).Sum(a => a.VoteValue)</span>
}

and the jQuery code is :

<script>
  $(document).ready(function() {
    $('a.btn-like').click(function(e) {
      e.preventDefault();
      $(this).attr("disabled", "disabled");
      $('#commentcounter').text(function(i, oldVal) {
        return parseInt(oldVal, 10) - 1;
      })
      $.ajax({
        url: '@Url.Action("CommentUp", "Posts")',
        data: {
          id: this.id
        }
      });
    });
  });
</script>

回答1:

Jquery Documentation

Attributes vs. Properties:

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

official documentation: http://api.jquery.com/prop/

For your example you need this:

 $(this).prop('disabled', true);


回答2:

use $(this).prop("disabled", true); to disable the button inside your click handler

How to increment comment counter

First if commentcounter is in loop it will get the same id that will produce an error you can do one thing that append @item.Id with the commentcounter id to make it unique so it should look like commentcounter12 , commentcounter23 if @item.Id = 12 or 23 etc for multiple commentcounters now write this code to increment

$('commentcounter'+e.target.id).text(parseInt($('commentcounter'+e.target.id).text())+1)