此代码简要显示了按钮单击设置的显示区域: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>
答案 0 :(得分:0)
您可以使用事件对象和d ata属性:
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>
答案 1 :(得分:0)
为防止刷新表单提交页面,您将需要使用event.preventDefault();
我相信您正在努力实现以下目标:
<div id="main">
<form>
<fieldset>
<button onclick="showHide('myDiv1')">Area 1</button>
<button onclick="showHide('myDiv2')">Area 2</button>
</fieldset>
</form>
</div>
<div id="myDiv1" style="display:none">
Area 1
</div>
<div id="myDiv2" style="display:none">
Area 2
</div>
<script>
function showHide(elemId) {
event.preventDefault();
var x = document.getElementById(elemId);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>