简体   繁体   中英

selecting django objects with jquery

I have objects of a model displayed in a template with a for loop like this:

{% for post in posts %}

 {{post.text}}

{% endfor %}

Now I want to attach a button to each post object which holds the post.id value and on clicking the button should make an ajax request that updates a vote attribute on that particular object.

So, I tried adding a button like this:

{% for post in posts %}

     {{post.text}}

<input type="submit" value="V" id="upButton" post_id="{{post.id}}"></input>

    {% endfor %}

Prior to ajax I just want to see if the buttons are working so I tried checking (using jQuery) if it alerts the post.id value of each post:

<script>
    $(document).ready(function(){
       $('#upButton').click(function(){
        var post_id = $('#upButton').attr('post_id');
        alert(post_id);
      });
    });
  </script>

Only the button on the first object is working. Other buttons are not working. What's happening here?

id attribute can be set only once per html page.

So the javascript code will refer only to the first element always.

Change it to:

<input type="submit" value="V" data-role="upButton" post_id="{{post.id}}"></input>

And in the javascript:

<script>
    $(document).ready(function(){
       $('[data-role=upButton]').click(function(){
        var post_id = $(this).attr('post_id');
        alert(post_id);
      });
    });
  </script>

It should work

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