[英]make div invisible and visible on button click using jquery
我有一个按钮,点击该按钮,我有一个显示和隐藏的div。 我用jquery实现了它。 但问题是页面加载时,div已经显示。 我想要,如果我点击按钮,那么只有div应该是可见的。
这是我的代码:
脚本:
<script>
$(document).ready(function() {
$('#btn').live('click', function(event) {
$('#div1').toggle('show');
});
});
</script>
HTML:
<input type="button" id="btn" class="btncss" value="filter" />
<div id="div1" runat="server" style="height:300px;width:300px;background-color:#f3fbd6">
<table>
<tr>
<td>
<asp:TextBox ID="txt" runat="server" TextMode="MultiLine"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:DropDownList ID="ddl" runat="server"></asp:DropDownList>
</td>
</tr>
</table>
<hr />
<table>
<tr>
<td>
<asp:Button ID="btncancel" runat="server" Text="cancel" />
</td>
<td>
<asp:Button ID="btnFilter" runat="server" CssClass="btncss" Text="Filter" />
</td>
</tr>
</table>
</div>
默认情况下使用CSS隐藏它:
#div1 {
display: none;
}
请注意,不推荐使用jQuery的live()
方法,不应使用它。 它被on()
取代。 此外,您的#div1
元素在其上设置了runat="server"
属性,这意味着ASP.Net将在运行时自动为该元素生成id
属性。 您需要使用ClientID
方法检索该id
:
$(document).on('click', '#btn', function() {
$('#<%= div1.ClientID %>').toggle();
});
您应该使用CSS将display:none
设置为#div1
。 采用:
#div1{
display:none;
}
即使它不是首选,你可以使用JS在document.ready()
隐藏你的div page load
,所以使用.hide()
,你的脚本变成:
<script>
$(document).ready(function ()
{
$('#div1').hide(); //ADD THIS
$('#btn').live('click', function (event)
{
$('#div1').toggle('show');
});
});
</script>
你可以用它
$('input').click(function() { if ($('input').val() === "show") { $('#div1').show('700'); $('input').val("hide"); } else{ $('#div1').hide('700'); $('input').val("show"); }; });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <input type="button" id="btn" class="btncss" value="show" /> <div id="div1" runat="server" style="height:300px;width:300px;background-color:#f3fbd6; display: none;"> <table> <tr> <td> <asp:TextBox ID="txt" runat="server" TextMode="MultiLine"></asp:TextBox> </td> </tr> <tr> <td> <asp:DropDownList ID="ddl" runat="server"></asp:DropDownList> </td> </tr> </table> <hr /> <table> <tr> <td> <asp:Button ID="btncancel" runat="server" Text="cancel" /> </td> <td> <asp:Button ID="btnFilter" runat="server" CssClass="btncss" Text="Filter" /> </td> </tr> </table> </div>
set display: none;
为#div1并使用我的脚本
由于您的#div1
元素具有runat="server"
意味着您使用的是asp.net,因此您应该使用Control.ClientID
应该使用CSS类来隐藏元素以及其他CSS规则
.myDiv {
display: none; //Hide it using CSS
height:300px;
width:300px;
background-color:#f3fbd6;
}
HTML ,将CSS类添加到div
<div id="div1" runat="server" class="myDiv">
</div>
脚本
$('#btn').live('click', function (event)
$('.myDiv').toggle();
//Or, You can use Control.ClientID
$("#<%= div1.ClientID %>").toggle();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.