关于下拉菜单有很多答案。但我从数据库中调用菜单项。
如果我单击某个菜单项 ( $table[0]
),则' . $table[0] . ' - content
显示内容 ( ),如果我再次单击,则内容消失。到现在为止还挺好。
问题是,如果某些内容已经打开并且我单击另一个菜单项,我会同时打开这两个内容。如何只允许打开最后一次选择并仍然保持切换功能......?
我尝试了很多东西,这是其中之一:
<?php
include 'connect_database.php';
$result = mysqli_query($con, "show tables");
while($table = mysqli_fetch_array($result)) {
echo '<button onclick="' . $table[0] . 'myFunction()">' . $table[0] . '</button><br />
<div id="' . $table[0] . '" style="display:none;" class="tabcontent">' . $table[0] . ' - content</div>
<script>
function ' . $table[0] . 'myFunction() {
var x = document.getElementById("' . $table[0] . '");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}}
</script>';
}
?>
非常感谢
您的问题是您没有跟踪创建的所有菜单。也myFunction
就是对所有的人都一样的,所以很可能是足够的定义只有一个:)我会做这样的:
<?php
include 'connect_database.php';
$result = mysqli_query($con, "show tables");
while($table = mysqli_fetch_array($result)) {
$name = $table[0];
echo "<button onclick='myFunction(\"$name\")'>$name</button><br /><div id='$name' style='display:none;' class='tabcontent'>$name - content</div>";
}
?>
<script>
function myFunction(id) {
registerId(id);
hideAll(id);
var x = document.getElementById(id),
s = x.style.display;
x.style.display = (s === "none") ? "block" : "none";
}
// register a new id so we know what to hide when needed
function registerId (id) {
var m = window.myMenus = window.myMenus || [];
if(m.indexOf(id) === -1) {
m.push(id);
}
}
// hide all registered menus except the id
function hideAll(id) {
var m = window.myMenus = window.myMenus || [],
i, l=m.length;
for(i=0;i<l;i++){
if(m[i] == id) continue;
var x = document.getElementById(m[i]);
x.style.display = 'none';
}
}
</script>
或者您可以跟踪最后打开的一个并仅关闭那个:D
php code remains the same as before
<script>
function myFunction(id) {
var x,old;
if(old = window.lastOpenId) {
x = document.getElementById(old);
x.style.display = "none";
delete window.lastOpenId;
}
if(id != old) {
x = document.getElementById(id);
x.style.display = "block";
window.lastOpenId = id;
}
}
</script>
请注意,在这两种情况下,script
都在while
循环之外和php
代码之外,因此只需要打印一次。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句