用一个按钮显示/隐藏div元素 [英] Show/Hide div element with one button
问题描述
我最近一直在潜入jQuery,并且非常喜欢在触发事件时如何显示/隐藏元素。我尝试添加一个简单的功能到我的测试网站,当登录按钮被点击时会显示登录表单,然后隐藏表单,如果再次点击该按钮,我使用的jquery函数只能工作一次(当我单击按钮并显示表单时),但是在显示表单后,如果我尝试再次单击按钮,则什么都不会发生。
jquery代码:
函数displayLoginBox(){
if($(#login_Box_Div:hidden)){
$(#login_Box_Div)。show();
$(#buttonLogin).css('color','#FF0');
$ b else if($(#login_Box_Div:visible)){
$(#login_Box_Div)。hide();
$(#buttonLogin).css('color','white');
HTML按钮代码:
< h3> < a href =#> Pictio< / a> < button id =buttonLoginonclick =displayLoginBox()> LogIn< / button>< / h3>
HTML div代码:
< div id =login_Box_Div>
< form name =myform>
< input type =textname =usernameplaceholder =Username/>
< input type =passwordname =passwordplaceholder =Password/>
< input type =submitid =submitLogin/>
< / form>
< / div>
我有一种感觉,jquery脚本只运行一次,然后完成,但我可能是错的。 使用 .toggle()
$ $ $ $ $'code $('#buttonLogin')。on('click',function(e){
$(#login_Box_Div)。toggle ();
$(this).toggleClass('class1')
});
.class1
{
color:orange;
$ / code>
您可以使用 toggleClass()
切换按钮的类
I have recently been diving into jquery and loved how you could show/hide elements when an event is triggered. I tried adding a simple feature to my test website that will show Login Form when the login button is clicked and then hide the form if the button is clicked again, however; the jquery function I am using only works once (when I click the button and display the form) but after the form is displayed if I try to click the button again nothing happens.
Jquery Code:
function displayLoginBox(){
if ($("#login_Box_Div:hidden")){
$("#login_Box_Div").show();
$("#buttonLogin").css('color', '#FF0');
}
else if($("#login_Box_Div:visible")){
$("#login_Box_Div").hide();
$("#buttonLogin").css('color','white');
}
}
HTML button code:
<h3> <a href= "#">Pictio </a> <button id = "buttonLogin" onclick = "displayLoginBox()">LogIn</button></h3>
HTML div code:
<div id = "login_Box_Div">
<form name = "myform" >
<input type = "text" name = "username" placeholder = "Username" />
<input type = "password" name = "password" placeholder= "Password" />
<input type = "submit" id = "submitLogin" />
</form>
</div>
I have a feeling that the jquery script only runs once and then is finished, but I could be wrong.
Try using .toggle()
$('#buttonLogin').on('click', function(e){
$("#login_Box_Div").toggle();
$(this).toggleClass('class1')
});
.class1
{
color: orange;
}
You can use toggleClass()
to toggle the class for the button
这篇关于用一个按钮显示/隐藏div元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!