首页 > 解决方案 > 使用 Javascript 使用动态 php ID 隐藏和取消隐藏 DIV

问题描述

我正在尝试隐藏和取消隐藏包含文本字段的 div 标签。这些文本字段将显示在每条记录上。当我使用单个字符串作为 id 时,我有这个函数可以工作,唯一的问题是它显示在所有行上。所以我决定添加一个与 ID 匹配的每一行的变量,这样当用户单击它时,它只显示该特定行的文本区域。下面是我的代码

Javascript:

<script>
    const targetDiv = document.getElementById("third");
    const btn = document.getElementById("<?php echo $author_id_4comm; ?>");
    btn.onclick = function () {
        if (targetDiv.style.display !== "none") {
            targetDiv.style.display = "none";
        } else {
            targetDiv.style.display = "block";
        }
    };    
</script>

HTML:

<a class='btn' id='$author_id_4comm' role='button' style='font-size:11px;color:#808080;' > Reply Comment</a>
<div id='third' style='display:none;'>Display textfield here</div>

现在的问题是,当我单击回复按钮时,隐藏的 div 仅显示在最后一行。

请帮助我!

标签: javascripthtmljquery

解决方案


为了保持DRY,我建议使用类而不是 ID。

根据您的代码结构,字段容器是按钮的直接兄弟。为每个按钮绑定一个点击事件。单击按钮后,找到其nextElementSibling及其toggle()“显示”类。

const btns = document.querySelectorAll(".btn");

function handleButtonClick() {
  let field = this.nextElementSibling;
  field.classList.toggle('field--show');
}

btns.forEach(btn => btn.addEventListener('click', handleButtonClick));
.btn {
  font-size: 11px;
  color: #808080;
}

.field {
  display: none;
}

.field--show {
  display: block;
}
<a class="btn" role="button">Reply Comment</a>
<div class="field">Display textfield here</div>
<a class="btn" role="button">Reply Comment</a>
<div class="field">Display textfield here</div>
<a class="btn" role="button">Reply Comment</a>
<div class="field">Display textfield here</div>


或者,如果您只想显示被单击的项目,请在显示目标字段之前隐藏所有字段:

const btns = document.querySelectorAll(".btn");
const fields = document.querySelectorAll(".field");

function handleButtonClick() {
  let field = this.nextElementSibling;
  fields.forEach(field => field.classList.remove('field--show'));
  field.classList.add('field--show');
}

btns.forEach(btn => btn.addEventListener('click', handleButtonClick));
.btn {
  font-size: 11px;
  color: #808080;
}

.field {
  display: none;
}

.field--show {
  display: block;
}
<a class="btn" role="button">Reply Comment</a>
<div class="field">Display textfield here</div>
<a class="btn" role="button">Reply Comment</a>
<div class="field">Display textfield here</div>
<a class="btn" role="button">Reply Comment</a>
<div class="field">Display textfield here</div>


推荐阅读