javascript - 使用 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 仅显示在最后一行。
请帮助我!
解决方案
为了保持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>
推荐阅读
- jquery - CSS 未找到 Codeigniter 4
- java - 如何从 MySQL 表中获取多个结果?
- android - Android工作室:活动被破坏后Android调用暂停
- php - 如何在 laravel 中使用 Vue axios 从数据库中获取数据?
- android - Flutter iOS 应用 - 在 TestFlight 中测试应用升级
- reactjs - TypeError: _firebase__WEBPACK_IMPORTED_MODULE_3__.default.auth 不是使用 firebase/react 进行身份验证的函数登录
- javascript - 2 Jquery ajax 发布请求。第二个给出错误:错误[ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头
- android - 安卓 | 如何在显示下一个对话之前关闭上一个对话?
- reactjs - Next.js monorepo:子域上的多个应用程序与一个应用程序?
- java - Apache CXF - Weblogic 12c (12.1.3) - 日志记录