1

我有一个 Django 模板,它呈现了一些关于用户的数据。它是一个 for 列表,它为每个用户遍历并创建此元素。我希望能够单击它并显示一个包含所有信息的模式。因此,如果我单击 user1,我会得到 user1 的信息,依此类推。我不知道该怎么做。

我目前正在尝试使用 JavaScript 来执行此操作。问题是我无法将特定元素中的数据导入 JavaScript。我有模式工作,因为它弹出。但是,我找不到从单击的特定用户那里检索数据的方法。

#dashboard.html
{% for party in parties %}
    <div class="userInfo">
        <img user="{{party}}" src="{% static 'restaurants/images/userIcon.png' %}">
        <div class="userText">
            <p>{{party.lastName}} </p></br>
        </div>
        <button name="remove"><a href="/restaurants/removeParty/{{party.id}}">Remove</a></button>
    </div>
{% endfor %}

我只需要通过单击的特定按钮将来自特定用户的数据获取到 js 中。也许有更好的方法来做到这一点?我不知道。我只需要能够使用来自特定用户点击的数据填充模式。上面的代码显示了创建用户信息的循环的 html。

4

1 回答 1

1

根据对象的大小,它可能有点冗长,但您可以使用数据属性:

{% for party in parties %}
    <div class="userInfo" data-lastName="{{party.lastName}}" data-etc="{{party.etc}}">
        <img user="{{party}}" src="{% static 'restaurants/images/userIcon.png' %}">
        <div class="userText">
            <p>{{party.lastName}} </p></br>
        </div>
        <button name="remove"><a href="/restaurants/removeParty/{{party.id}}">Remove</a></button>
    </div>
{% endfor %}

然后在单击打开模式时访问它们:

const users = document.querySelectorAll('.userInfo');

for (let i = 0; i < users.length; i++) {
  users[i].addEventListener('click', function() {
    const userData = {
           lastName: this.dataset.lastName,
           etc: this.dataset.etc
        }
    openMyModal(userData);
  })
}
})
于 2019-07-29T20:32:53.620 回答