gpt4 book ai didi

JavaScript CSS 模态未显示正确的信息

转载 作者:行者123 更新时间:2023-12-03 03:28:48 25 4
gpt4 key购买 nike

所以我在 Flask 中使用 Jinja2 模板来渲染 HTML 文档。我将一个名为“healthy_alerts”的字典传递到 Jinja 模板中。字典片段如下所示(敏感值被操纵):

healthy_alerts = {
...
"52.NE": {
"appliance_id": 123456,
"severity": "green",
"ip": "x.x.x.x",
"hostname": "HG-EDGE-FranceAntony-ECV01",
"serial": "11-11-11-11-11",
"critical_alarms": 0
},
"6.NE": {
"appliance_id": 7891011,
"severity": "green",
"ip": "y.y.y.y",
"hostname": "HG-EDGE-Schiltach-ECV01",
"serial": "22-22-22-22-22",
"critical_alarms": 0
}
}

这是一个代码片段:

<div id="alarms" align="center">

{% if healthy_alerts %}
<div class="healthy_div">
{% for dev in healthy_alerts %}
<button class="btn_healthy" id="{{ healthy_alerts.get(dev).get('hostname') }}Btn"></button>


<div id="{{ healthy_alerts.get(dev).get('hostname') }}Modal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">&times;</span>
<p>{{ healthy_alerts.get(dev) }}</p>
</div>
</div>

<script>
// Get the modal
var modal = document.getElementById('{{ healthy_alerts.get(dev).get("hostname") }}Modal');

// Get the button that opens the modal
var btn = document.getElementById("{{ healthy_alerts.get(dev).get("hostname") }}Btn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
{% endfor %}
</div>
{% endif %}
</div>

似乎一切都差不多了,但唯一的问题是当我单击任何模式按钮时,它总是显示相同的条目(“6.NE”)。

当我检查 Chrome 中的页面时,我可以看到所有模式都填充了正确的信息。但是,正如您从以下 chrome 输出中看到的那样,当我单击模式按钮时,无论如何它仍然始终显示相同的信息(“6.NE”条目)。

我认为这可能是一些微不足道的 JavaScript 问题,但我不是 JavaScript 编码员。 enter image description here

最佳答案

我对 Jinja 不熟悉,但根据 JavaScript 代码,我想说这是因为你没有正确确定变量的范围,所以它们被视为全局变量。变量modal , buttonspan未在函数中声明,因此尽管使用 var,它们仍将被视为全局变量。即使您的每个<script>标签是分开的,它们仍然共享相同的全局变量。只是modal这是一个问题,因为它在事件处理程序内部使用,并将引用分配给 modal 的最后一个值。 .

如果将该脚本代码包装在 IIFE 中,应该没问题:

(function() {
// Get the modal
var modal = document.getElementById('{{ healthy_alerts.get(dev).get("hostname") }}Modal');

// ...

window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
})();

如果您不熟悉 IIFE:

https://developer.mozilla.org/en-US/docs/Glossary/IIFE

关于JavaScript CSS 模态未显示正确的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46186886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com