【问题标题】:Hide div on button press按下按钮时隐藏 div
【发布时间】:2021-03-21 17:43:48
【问题描述】:

如下图所示,我想在回复按钮下方显示 div。

(Div 是文本框和发送按钮)

下面的代码可以正常工作,除非您按下哪个回复按钮,文本框在第一个回复按钮上打开,这是由隐藏 MyDiv 的 javascript 函数和每个 ID 是 MyDiv 引起的。问题在于这需要是动态的,因为我不知道我会有多少消息。

这不是所有代码,但应该足以了解发生了什么。

更新了最少的代码

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#myDIV {
  width: 100%;
  padding: 50px 0;
  text-align: center;
  background-color: lightblue;
  margin-top: 20px;
  display: none;
}
</style>
</head>
<body>

<p>Example</p>

<button onclick="myFunction()">Try it</button>

<div id="myDIV">
This is my DIV element.
</div>
<br/>
<br/>
<button onclick="myFunction()">Try it</button>

<div id="myDIV">
This is my DIV element.
</div>
<br/>
<br/>
<button onclick="myFunction()">Try it</button>

<div id="myDIV">
This is my DIV element.
</div>

</body>
</html>


function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "block") {
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }
}

https://jsfiddle.net/vzcq7t0e/

谢谢

编辑

与这个问题类似,但如上所述,我需要它是动态的。

Display div and hide another div by button press

编辑 2

我还在为此苦苦挣扎。我一直在尝试使用 jquery $(this).parent().hide();

但没有运气。我应该继续使用这种方法还是尝试其他方法?

【问题讨论】:

  • “并且每个 ID 都是 MyDiv” - 这就是问题所在,ID 必须在 HTML 文档中是唯一的。
  • 是的,但如何动态?
  • 使用一个类并委托给公共父元素 - 如果您单击 [&lt;&gt;] sn-p 编辑器并创建了一个 minimal reproducible example 我们可以向您展示
  • 代码更新为最小示例

标签: php html api bootstrap-4


【解决方案1】:

所以我解决了。将计数 ID 添加到 ID 标签和一个隐藏所有 div 的类,然后显示具有请求 ID 的 div。

<div <?php echo 'id="myDIV ' . $x . '"' ?> class="reply" style="padding-top: 30px;">  

<style>
    .reply{
        display: none;
    }
#myDIV {
  width: 100%;
  margin-top: 30px;
  display: none;
}
</style>

<script>
function myFunction(divid) {
  var x = document.getElementById("myDIV " + divid);
  if (x.style.display === "block") {
    x.style.display = "none";
  } else {
    document.querySelectorAll('.reply').forEach(function(el) {
        el.style.display = 'none';
    });
    x.style.display = "block";
  }
}
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多