I am developing an application using Asp.net mvc and jquery. I'd like to use the same naming convention (classes and ids) for html elements in different views.
In case when I want to load a partial view asynchronously, the $(document).ready() piece of code in the main view loses its usefulness because none of the patial view's html tags and css naming is recognized by jquery. I certainly do not want to write the same code for every view. What's th ebest way to solve this issue?
$( document ).ready()A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
The key difference between $(document). ready() and $(window). load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc.
Can we add more than one 'document. ready' function in a page? Yes we can do it as like I did in below example both the $(document). ready will get called, first come first served.
To create a partial view, right click on Shared folder -> select Add -> click on View.. Note: If the partial view will be shared with multiple views, then create it in the Shared folder; otherwise you can create the partial view in the same folder where it is going to be used.
You can use .live()
for this, for example:
$(".myClass").click(function() { });
Becomes this:
$(".myClass").live('click', function() { });
.live()
works in a different way. .click()
binds to the elements the selector matched when it ran, usually document.ready
. .live()
works by living at the DOM root, listening for events to bubble and executing the handler if the event that bubble's target matches the selector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With