我正在建立一个关于我们的页面,我希望使用JavaScript来显示/隐藏/替换DIV的内容,并根据用户单击的内容将其与愿景声明或个人简历一起显示。我是使用脚本的新手,所以我希望以前有人这样做。
我目前有一个用于生物的按钮和一个用于视觉的按钮,虽然我可以毫无问题地显示和隐藏文本,但我不知道如何替换DIV,以免生物和视觉不能同时显示。
这是我到目前为止的内容:
function showhide(id) {
var e = document.getElementById(id);
e.style.display = (e.style.display == 'block') ? 'none' : 'block';
}
<button type="button" onclick="javascript:showhide('vision')">Vision</button>
<button type="button" onclick="javascript:showhide('bio')">Bio</button>
<div id="vision" style="display: none;">
<p>This is my vision</p>
</div>
<div id="bio" style="display: none;">
<p>This is my bio</p>
</div>
我还希望按钮文字也可以根据显示的内容更改为“ Hide Bio”或“ Hide Vision”。
如果有人可以提供帮助,那么像我这样的Java Noob将非常感激。
这也是我第一次使用这样的论坛,因此希望获得任何指示或反馈...一定要从某个地方开始,对吗?
逻辑有两个问题。如果显示/隐藏一个div,则仍然需要隐藏/显示第二个div。因此,您可以添加更多代码行来执行此操作..或者简单地,您可以使用一个div并根据单击的按钮来更新其内容。
因此,您可以尝试以下操作:
<script>
var textStrings = {"author1": {"Vision":"this is author1 vision", "Bio":"this is author1 bio"},
"author2": {"Vision":"this is author2 vision", "Bio":"this is author2 bio"},
"author3": {"Vision":"this is author3 vision", "Bio":"this is author3 bio"}};
function showhide(element) {
reset();
var id=element.id;
var author = document.getElementById("authors").elements["authors"].value;
var flag = document.getElementById('content').innerHTML == textStrings[author][id];
document.getElementById('content').innerHTML = flag ? "" : textStrings[author][id];
element.innerHTML = flag ? id : "hide " + id;
}
function reset(){
for (var k in textStrings["author1"]){
document.getElementById(k).innerHTML = k;
}
}
function resetAuthor(){
document.getElementById('content').innerHTML = ""
reset();
}
</script>
<form id="authors">
<input type="radio" name="authors" id="author1" onchange="resetAuthor()" value="author1" checked> author 1
<input type="radio" name="authors" id="author2" onchange="resetAuthor()" value="author2"> author 2
<input type="radio" name="authors" id="author3" onchange="resetAuthor()" value="author3"> author 3
</form>
<div style="display:inline">
<button type="button" id="Vision" onclick="javascript:showhide(this)">Vision</button>
<button type="button" id="Bio" onclick="javascript:showhide(this)">Bio</button>
</div>
<div style="display: block;">
<p id="content"></p>
</div>
如果再次按下按钮,此代码还会将内容切换/设置为空。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句