不能对 post 的磁带中的每个 post 使用带有 ajax 的点赞按钮
Can't use like button with ajax for each post in tape of posts
所以,每个 post 我都有一个赞按钮。但是我的 ajax 只捕获新事件 post。
请解释为什么 ajax 没有为磁带中的每个 post 制作它。以及如何修复它。
这是一个 ajax 代码。
{% block jquery %}
$("#po-like").click(function(event){
event.preventDefault();
$.ajax({
url: $("#po-like-href").attr('href'),
success: function(){
},
error: function(response, error){
}
})
});
{% endblock %}
这是我的 posts 的磁带。
{% for post in tape %}
...
{{ post.text }}
...
<a id="po-like-href" href="/like_post/{{ post.id }}/">
<img id="po-like" src="{% static "" %}"/>
</a>
{% endfor %}
所有其他 post 的点赞按钮就像根本没有 ajax 一样工作。如果我点击它们,页面会重新加载并且点赞数会发生变化
这是因为所有 a
标签中的相同 id's
。在一个 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 %}
所以,每个 post 我都有一个赞按钮。但是我的 ajax 只捕获新事件 post。 请解释为什么 ajax 没有为磁带中的每个 post 制作它。以及如何修复它。
这是一个 ajax 代码。
{% block jquery %}
$("#po-like").click(function(event){
event.preventDefault();
$.ajax({
url: $("#po-like-href").attr('href'),
success: function(){
},
error: function(response, error){
}
})
});
{% endblock %}
这是我的 posts 的磁带。
{% for post in tape %}
...
{{ post.text }}
...
<a id="po-like-href" href="/like_post/{{ post.id }}/">
<img id="po-like" src="{% static "" %}"/>
</a>
{% endfor %}
所有其他 post 的点赞按钮就像根本没有 ajax 一样工作。如果我点击它们,页面会重新加载并且点赞数会发生变化
这是因为所有 a
标签中的相同 id's
。在一个 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 %}