gpt4 book ai didi

用于显示/隐藏页面区域的 javascript 按钮不会保持切换状态

转载 作者:行者123 更新时间:2023-12-03 01:30:38 25 4
gpt4 key购买 nike

这段代码简单地显示了按钮单击设置的显示: block 区域,但随后该区域立即消失。无论出于何种原因,该区域的切换都不会粘住。请指教:

<html>
<head>
<script type="text/javascript">
function ShowHide(input) {
if (input == "look"){
document.getElementById("1").style.display = "block";
} else {
document.getElementById("2").style = "display:block";
}
return;
}
</script>
</head>
<body>
<div id="main">
<form >
<fieldset>
<button onclick="ShowHide('1')">Area 1</button>
<button onclick="ShowHide('2')">Area 2</button>
</fieldset>
</form>
</div>
<div id="1" style="display:none">
Area 1
</div>
<div id="2" style="display:none">
area 2
</div>

最佳答案

您可以使用事件对象和数据数据属性:

function ShowHide(input) {
// If you don't want the form to refresh the page, use preventDefault
event.preventDefault();
// Using dataset you can access the data attributes from the button that fired the event
document.getElementById(event.target.dataset.divid).style.display = "block";
}
<div id="main">
<form >
<fieldset>
<button onclick="ShowHide()" data-divid="1">Area 1</button> <!- Add data attributes to your buttons ->
<button onclick="ShowHide()" data-divid="2">Area 2</button>
</fieldset>
</form>
</div>
<div id="1" style="display:none">
Area 1
</div>
<div id="2" style="display:none">
area 2
</div>

关于用于显示/隐藏页面区域的 javascript 按钮不会保持切换状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51326578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com