所以,我对每个帖子都有一个“赞”按钮。但我的 ajax catch 事件仅适用于新一篇文章。 请解释一下为什么 ajax 不能适用于磁带中的每个帖子。以及如何修复它。
这是一个ajax代码。
{% block jquery %}
$("#po-like").click(function(event){
event.preventDefault();
$.ajax({
url: $("#po-like-href").attr('href'),
success: function(){
},
error: function(response, error){
}
})
});
{% endblock %}
这是我的帖子磁带。
{% for post in tape %}
...
{{ post.text }}
...
<a id="po-like-href" href="/like_post/{{ post.id }}/">
<img id="po-like" src="{% static "" %}"/>
</a>
{% endfor %}
所有其他帖子的类似按钮都可以正常工作,就好像根本没有ajax一样。如果我点击它们,页面会重新加载并且喜欢的数量会发生变化
最佳答案
这是因为所有 a
标记中的 id
相同。一个 html 页面中只能有一个 uniq #id。相反,您可以将其更改为 .class
。
{% block jquery %}
$(".po-like").click(function(event){
//changing #id to .class
//added the below line
var img = $(this);
event.preventDefault();
$.ajax({
url: img.parent().attr('href'),
success: function(){
},
error: function(response, error){
}
})
});
{% endblock %}
{% for post in tape %}
...
{{ post.text }}
...
//changing #id to .class
<a class="po-like-href" href="/like_post/{{ post.id }}/">
<img class="po-like" src="{% static "" %}"/>
</a>
{% endfor %}
关于javascript - 无法对帖子磁带中的每个帖子使用带有 ajax 的 Like 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38037490/