简体   繁体   中英

Loading jQuery from ASP.NET User Control ascx page?

Can you put jQuery code in a .ascx page ?

I have a user control that I use in a ASP.NET project. Multiple instances of that control are dynamically created when I select something on the default.aspx page. I want to manipulate parts of that user control with jQuery. However, jQuery doesn't seem to be loading.

I reference jQuery library in my MasterPage. I tested the following code from my default.aspx and it works, but I get no response when I use the same code from within my ascx page:

<script type="text/javascript" charset="utf-8">
    if (typeof ($) != 'function') alert('This component requires jQuery.');
    else $(function () { alert('The DOM is ready for jQuery manipulation.'); });
</script>

Any ideas ?

Thx.

if you've referenced jQuery in masterpage, then you can access it in .ascx.

can you put this inside $(document).ready(function(){ /* your code.. */ }); -in ascx- and check?

To include and run JavaScript or JQuery lines of code in a user control .ascx, does not should be inserting the <script> tag in the HTML code. Use that only to insert the references to JQuery files if those are need it. ASP.NET Page events like Load or UpdatePanel User control does not necessarily trigger the client-side events, such as when the load is complete on .aspx page. To get that, you should use ScriptManager.RegisterClientScriptBlock. To success with your sample, set up this code in the Load event of your .ASCX control:

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ActivateJsSample", 
@"<script type = 'text/javascript'>
if (typeof ($) != 'function') alert('This component requires jQuery.');
else $(function () { alert('The DOM is ready for jQuery manipulation.'); });
});
</script>", false);

This would sync and fire with the Load event of your user control, and fire up every time.

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