[英]selecting django objects with jquery
我在一個帶有for循環的模板中顯示了模型的對象,如下所示:
{% for post in posts %}
{{post.text}}
{% endfor %}
現在,我想將按鈕附加到每個具有post.id值的post對象,單擊該按鈕應發出ajax請求,以更新該特定對象的表決屬性。
因此,我嘗試添加這樣的按鈕:
{% for post in posts %}
{{post.text}}
<input type="submit" value="V" id="upButton" post_id="{{post.id}}"></input>
{% endfor %}
在ajax之前,我只想查看按鈕是否正常工作,因此我嘗試檢查(使用jQuery)它是否提醒每個帖子的post.id值:
<script>
$(document).ready(function(){
$('#upButton').click(function(){
var post_id = $('#upButton').attr('post_id');
alert(post_id);
});
});
</script>
只有第一個對象上的按鈕起作用。 其他按鈕不起作用。 這里發生了什么事?
每個html頁面只能設置一次id
屬性。
因此,javascript代碼將始終僅引用第一個元素。
更改為:
<input type="submit" value="V" data-role="upButton" post_id="{{post.id}}"></input>
在javascript中:
<script>
$(document).ready(function(){
$('[data-role=upButton]').click(function(){
var post_id = $(this).attr('post_id');
alert(post_id);
});
});
</script>
它應該工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.