我創建了一個視圖來生成帖子,每個帖子都有一個comments_set,它會生成用戶所做的所有評論。當發佈新評論時,執行下面的功能。jquery .click()事件問題(django)
$("#comment-post-button").click(function(){
var event_id = document.getElementById('event-id').value;
var url= '/post-comments/'+event_id +'/';
var data = {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
content:document.getElementsByName('comment-post-content')[0].value
}
$.post(url , data, function(){
$("#refresh-comments").load("/comments/" + event_id + '/', function(){
$("#comment-post-content").val("");
});
});
$("#comment-post-content").val("");
return false;
});
問題是,頁面包含多個帖子,每個評論提交按鈕都有相同的id「comment-post-button」。所以上面的函數只適用於頂部帖子,而不適用於其他帖子。我可以看到問題是什麼,但不知道如何解決這個問題。請幫忙。
下面是HTML標記:
{% for event in events %}
<div class="post">
<div class="post-right">
<div class="post-author"><a href="/{{ event.author.username }}/">{{ event.author.first_name }}</a></div>
<div class="post-content">{{ event.description }}</div>
<div class="post-bar">
<div class="post-likes">{{ event.up_votes }}<a href="#"><img src="/site-media/static/images/like.png" /></a></div>
<div class="post-dislikes">{{ event.down_votes }}<a href="#"><img src="/site-media/static/images/dislike.png" /></a></div>
<div class="post-timestamp">{{ event.pub_date }}</div>
<a href="#" class="post-comment-link">Comment</a>
</div>
<div class="post-comment">
<form method="post" action="/post-comments/{{ event.id }}/">
{% csrf_token %}
<input type="text" id="comment-post-content" name="comment-post-content" maxlength="200" placeholder="Add a comment..." />
<input type="hidden" id="event-id" value="{{ event.id }}">
<input type="submit" id="comment-post-button" class="comment-post-button" value="Post comment" />
</form>
</div>
<div id="refresh-comments" class="comments">
{% include "comments.html" %}
</div>
</div>
<div class="post-left">
<a href="#"><img src="../FestJanta/site-media/static/images/post.jpg" /></a>
</div>
</div>
{% endfor %}
comments.html:
{% for comment in event.comment_set.all|slice:"3" %}
<div class="comments-right">
<a href="/{{ name }}/" class="first_name">{{ comment.author.first_name }}</a>
{{ comment.content }}<br>
<div class="comment-timestamp">{{ comment.pub_date }}</div>
</div>
<div class="comments-left"><a href="#"><img src="../FestJanta/site-media/static/images/comment.jpg" /></a></div>
{% endfor %}
最終有效的解決方案:
$(".comment-post-button").click(function(){
var btn = $(this);
var currentPost = btn.parents('.post');
var event_id = currentPost.find('.event-id').val();
var url= '/post-comments/'+event_id +'/';
var data = {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
content:currentPost.find('input[name="comment-post-content"]').val()
}
$.post(url , data, function(){
$(currentPost.find('.refresh-comments')).load("/comments/" + event_id + '/', function(){
$(currentPost.find('.comment-post-content')).val("");
});
});
return false;
});
可以提供相同的類到所有Post按鈕,然後通過類 –
或枚舉ID訪問它們 – karaxuna
@AjinderSingh但是,這將如何解決問題。我需要唯一標識一個帖子按鈕 – toothie