首页 > 解决方案 > 按钮 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";
}

标签: javascripthtml

解决方案


鉴于您显示的 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>

推荐阅读