简体   繁体   中英

Custom jQuery show/hide div JS not working in ASP.Net

I have a master page that have script manager and Javascript/Jquery added in it. See below:

<asp:ScriptManager ID="SM" runat="server" EnablePartialRendering="true">
    <Scripts>
        <asp:ScriptReference Path="~/Scripts/jquery-1.7.2.min.js" ScriptMode="Release" />
        <asp:ScriptReference Path="~/Scripts/Custom.js" ScriptMode="Release" />
    </Scripts>
</asp:ScriptManager>

Custom Js:

$(".section").click(function () {  
    if ($(this).next(".sectiondetail").is(":hidden")) {
        $(this).next(".sectiondetail").slideDown("slow");
        $(this).children('span').text('[-]');
} else {
        $(this).next(".sectiondetail").slideUp("slow");
        $(this).children('span').text('[+]');
}
});

I have placed following html in my ASCX control that is added in content page that uses my master page:

<div class="section">
    <span>[+]</span> General Information
</div>
<div class="sectiondetail" style="display: none;">
     Details go here.
</div>

The JS function does not work as expected. If i add JS function in my ASCX control page, it works as expected. What is wrong here?

Thanks.

The time you are binding click event you may not have html controls ready/rendered with css section . On will make sure to add click event even the elements are added or rendered after this script block bind click.

$(".section").on("click", function () {  
    if ($(this).next(".sectiondetail").is(":hidden")) {
        $(this).next(".sectiondetail").slideDown("slow");
        $(this).children('span').text('[-]');
} else {
        $(this).next(".sectiondetail").slideUp("slow");
        $(this).children('span').text('[+]');
}
});

Or You can bind event when document is ready.

$(function(){
$(".section").click(function () {  
    if ($(this).next(".sectiondetail").is(":hidden")) {
        $(this).next(".sectiondetail").slideDown("slow");
        $(this).children('span').text('[-]');
} else {
        $(this).next(".sectiondetail").slideUp("slow");
        $(this).children('span').text('[+]');
}
});
});

Use style="visibility: hidden;" instead of style="display: none;"

<div class="sectiondetail" style="visibility: hidden;">
    Details go here.
</div>

If you are using following code,

$(this).next(".sectiondetail").is(":hidden")

OR You may Use;

$(this).next(".sectiondetail").css('display') == 'none'

In your current scenario ie style="display: none;"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM