【发布时间】:2022-01-12 11:28:50
【问题描述】:
我目前正在为 CS50w - 网络开发一个项目 4。其中一项任务是添加一个编辑帖子按钮(用于编辑登录用户(仅所有者)创建的帖子),该按钮执行此异步操作。因为存储帖子我使用的是 Django 模型,所以我使用 Django(以及它的模板功能)来向用户显示所有帖子,以及一个编辑按钮(如果用户也是帖子的创建者)。我在 div 中显示所有帖子。这意味着编辑按钮也是这个div的一部分...意思是我只能给它一个类或id来引用,但是我不知道如何区分它们,以及如何知道是哪一个(从哪个帖子)被点击,这样我就可以编辑那个帖子,而不是第一个出现 DOM 中的 JS 的帖子......无论如何这里是代码:
Django 中的 HTML:
{% for post in posts %}
<div class="post">
<a href="{% url 'users' post.user.username %}">{{ post.user }}</a>
<p>{{ post.content }}</p>
<p>{{ post.created }}</p>
{% if user.is_authenticated and user == post.user %}
<button class="edit_post_button">Edit Post</button>
{% endif %}
</div>
<div class="edit_post" style="display: none;">
<a href="{% url 'users' post.user.username %}">{{ post.user }}</a>
<textarea rows=3 cols=20>{{ post.content }}</textarea>
<p>{{ post.created }}</p>
<button class="save_edit_post_button">Save</button>
</div>
{% endfor %}
这是我写的那个不起作用的小 JS(我刚开始学习它,想用 vanilla JS 完成这个项目):
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('.edit_post_button').forEach(edit_post_button => {
edit_post_button.addEventListener('click', edit_post);
})
});
function edit_post(event) {
document.querySelector('.post').style.display = 'none';
document.querySelector('edit_post').style.display = 'block';
}
【问题讨论】:
-
您的标记中的
<edit_post>标记在哪里?
标签: javascript django dom-events addeventlistener