[英]Show One Div and Hide Another Div when Click on button
What I want to do is, when I click on button then one div should disappear and another should appear and if i click on the same button one more time, then first one should appear and second one should disappear. 我想做的是,当我单击按钮时,一个div应该消失,而另一个应该出现,如果我再单击同一按钮一次,那么第一个应该出现,第二个应该消失。 This would go until I click on the button.
直到我单击按钮。
What I tried: 我试过的
JavaScript: JavaScript:
function change_image(){
var flag = true;
if(flag){
document.getElementById('speaker_main_div_with_rounded_image').style.display="none";
document.getElementById('speaker_main_div_with_square_image').style.display="block";
flag = false;
} else {
document.getElementById('speaker_main_div_with_rounded_image').style.display="block";
document.getElementById('speaker_main_div_with_square_image').style.display="none";
flag = true;
}
}
HTML: HTML:
<input type="button" value="Click Here to get another image" onClick="change_image(this)">
Any help would be grateful. 任何帮助将不胜感激。
Thank You. 谢谢。
Your flag
variable is local, and its value is always the same when function is called. 您的
flag
变量是局部变量,调用函数时其值始终相同。 Initialize it with: 初始化它:
var flag = document.getElementById('speaker_main_div_with_rounded_image').style.display !== 'none';
This is my solution using jQuery Library . 这是我使用jQuery Library的解决方案。
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("#div1").toggle(); $("#div2").toggle(); }); }); </script> <style> .hide{ display:none; } </style> </head> <body> <button type="button" id="btn1">Toggle</button> <div id ="div1"> I am div 1 </div> <div id ="div2" class="hide"> I am div 2 </div> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.