jQuery with ASP.NET
1. Download jQuery library from jQuery web site, unzip the file and add/include the file in your project.
2. Create a simple ASPX page called jqueryDemo.aspx, and add <script> tag in the header section to reference the jQuery library.
3. Create an ASP:HyperLink control as follows
4. Add the following code snippet in the <head> section of the page
$(document).ready() will check if the document structure is fully parsed and the DOM tree is ready before executing the script in the function block. It has the same effect as the following line:
Why is it not working?
Put all pieces together, we have an ASPX page as follows:
However, when you load the above page in browser, you may find that there is no alert box when clicking on the hyperlink. So what is going on here?
First, let’s take a look at the page source generated in IE 8:
Nothing seems to be troublesome here. Now let’s take a look at the page source generated in FireFox:
Aha, thanks to the nice page source viewer of FireFox with the syntax highlight, I found the problem. The “/>” tag supposes to be a close tag of <script>, but somehow, browser got confused by the mixed usage of <script /> and </script> tags in the <head> section, and didn’t know how to correctly parse the code…and it tried its best to match <script /> with </script> as a pair. It is what caused the onclick event not fire. It looks like a browser bug to me.
Always explicitly close a tag with the old fashion. Now let’s change the <script> block in ASPX page as follows:
then load the page in browser, and viola, “Hello world” alert box pops up when clicking on the hyper link.
Hope this may help someone.