简体   繁体   中英

Looking to rename Django Ajax “like” button, but not working

Currently my button functions, but I've placed it inside of a django for loop. I'd like to move the js logic to a separate file, but first I need to give it a better name. Here is a snippet of my code:

{% for post in posts %}

.....

<script type="text/javascript">
  function toggleLike{{post.id}}(){
        $.ajax({
          url: "{% url 'photo_blog-post_like_api' post.id %}",
          success: function(data) {
            $("#likeCount{{post.id}}").html(data.like_count + ' likes');
            $('#imageElement{{post.id}}').html(data.img);
          }
          });
      };
</script>
<a id=imageElement{{post.id}}  onclick="toggleLike{{post.id}}()"><img src="/media/nav_buttons/liked.svg" height="17" width="17"></a>
....
<post info here>
....

{% endfor %}

When I remove the {{post.id}} from the function name, and onclick call, the button only functions for the post on the bottom of the page. All of the other buttons toggle the information for that one post. How can I give this function a general name, but still have it interact uniquely with each post?

You shouldn't be doing this as part of the name anyway. The post id is a parameter. The only collocated part is working out how to pass it to the Django URL tag

function toggleLike(post_id){
    $.ajax({
      url: "{% url 'photo_blog-post_like_api' "00000" %}".replace("00000", post_id)
      success: function(data) {
        $("#likeCount" + post_id).html(data.like_count + ' likes');
        $('#imageElement' + post.id).html(data.img);
      }
      });
  };
</script>
<a id=imageElement{{post.id}}  onclick="toggleLike({{post.id}})"><img src="/media/nav_buttons/liked.svg" height="17" width="17">

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