问题
I have a view where templates are nested within and the final template has a post with like and comment buttons/anchor tags.
The number of posts are not fixed and are populated dynamically and likes and comments are associated to a single post.
The last child template retrieves the posts generated. The issue is with the snippet:
---under dynamic loop---
<a href="" class="like" data-catid="{{ post.id }}">Like</a>
---under dynamic loop---
The above snippet is called by jQuery:
<script>
$('.like').on("click", function (event){
event.preventDefault();
var postid = $(this).attr("data-catid");
alert(postid);
$.ajax({
.
.some Ajax stuff...
.
</script>
Now the problem is that whenever I click any like of any post, then I receive the alerts as many times as the number of posts. It happened since the number of posts are not certain and are dynamically generated. So for every post I have a generated anchor tag with class 'like'. Please guide as to how to get only the single event upon the exact link clicked by the user.
Please refer my previous post if you seek to know the models also: Django Dynamic Object Filtering issue in Template
回答1:
I solved it by taking all jQuery stuff one template level up i.e. to the parent template of the stated child template above. Apart form that I had to use the CSRF Cookie getting and sending CSRF request functions as stated in Django documentation.
来源:https://stackoverflow.com/questions/61483288/how-to-track-click-event-on-auto-generated-html-elements-in-template-via-jquery