javascript - 按钮 OnClick 仅返回适用于第一个元素
问题描述
我是网页设计的新手。我有多个生成的 MySQL 数据库元素行,我想对其进行更改,但是当我单击按钮显示时,即使我单击第二个或第三个“添加”,它也只显示第一个按钮。
<body>
{% for trail in trails %}
<div>
<form>
{% csrf_token %}
TrailName:{{trail.1}}
AreaName:{{trail.2}}
City:{{trail.3}}
Length:{{trail.8}}
RouteType:{{trail.11}}
AvgRating{{trail.12}}
</form>
<button onClick="show()">Add</button>
</div>
<div class="part">
<form action="insert_schedule" method="POST">
{% csrf_token %}
<input type="radio" name="trailid" value="{{trail.0}}">
schedule date:
<input type="date" name="schedule_date">
<input type="submit" value="Ok">
</form>
<button onClick="hide()">Cancel</button>
</div>
{% endfor %}
</body>
function show() {
var show_part = document.querySelector(".part");
show_part.style.display = "block";
}
function hide() {
var show_part = document.querySelector(".part");
show_part.style.display = "none";
}
解决方案
鉴于您显示的 HTML 结构:
function show(el){
const show_part = el.parentElement.nextElementSibling;
show_part.hidden = false;
}
function hide(el){
const show_part = el.parentElement;
show_part.hidden = true;
}
并将您的button
代码更改为
<button type="button" onclick="show(this)">Cancel</button>
.
.
.
<button type="button" onclick="hide(this)">Cancel</button>
推荐阅读
- sql-server - 将数据从逗号分隔的字符串插入表 (T-SQL)
- android - 哪个是android中最好的pdf查看器?
- angular - 如何制作圆形的多条线滑块?
- apache-spark - to_date() 接受 1 个位置参数,但给出了 2 个
- java - 如何使用 JSON 填充子项目微调器?
- python - 如何在不遗漏任何东西的情况下检测所有矩形框python opencv
- selenium - 尝试通过 Windows 应用程序驱动程序启动计算器时无法创建新的远程会话
- python - 无法使用 tf.keras 完成 Conv1D
- mysql - 在 Sequelize 中从其他表中查找计数
- javascript - 使用 google-maps-react 绘制多个多边形