How to track click event on auto generated HTML elements in Template via jQuery in Django

久未见 提交于 2020-04-30 06:25:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!