简体   繁体   中英

JQuery Doesn't seem to work for server control

I tried to call jQuery function from my aspx page but it doesn't fire although it was working fine before but I think something happened that causes like this issue.

I have a div works as a button:

<div id="BtnContainer" runat="server" class="BtnContainer">add container</div>

and I need when click on it to show another popup div

I am using this code:

<script type="text/javascript">
    $(document).ready(function () {
        $("#BtnContainer").click(function () {
            alert("working");
            $("#ContainerPanel").slideToggle("slow");
        });
    });
</script>

I have included the jquery library via internet and local files but no one works:

<script type="text/javascript" src="<%# ResolveUrl("assets/js/jquery.js") %>"></script>

and tried

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Be informed that I tried the above in simple html file and it works fine and the alert was fired.

Is there any solution ?

Inspect your HTML when the page renders. Since you're using runat="server" on the element the ID is being altered on you.

Instead try using the class name to identify the element you want to attached the click event to.

$(document).ready(function () {
    $(".BtnContainer").click(function () {
        alert("working");
        $("#ContainerPanel").slideToggle("slow");
    });
});

You could use the <%=BtnContainer.ClientID=> property to get the real ID as others have suggested but then you need to have your javascript inside your .aspx page instead of nice and tidy in a (minified) .js file.

Mixing the C# aspect with the JS gets a bit ugly (IMO).

Since you have runat='server' , ASP.NET will generate different ID for your div . Check it in HTML. You will have to use <%=BtnContainer.ClientID=> to generate correct ID in your script (inside of your .aspx):

$("<%=BtnContainer.ClientID=>").click(function () {
     alert("working");
     // more code here
});

or maybe select it through a class DOM property like so:

$(".BtnContainer").click(function () {
     alert("working");
     // more code here
});

When you put an element in a PlaceHolder it prepends PlaceHolderName_ to your ID

Try Using

$("#MainPlaceHolder_BtnContainer")

In your document.ready your id should be <%=btndiv.ClientId%>. Sorry for the bad formatting, doing this from stackexchange app

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