使用jQuery.load加载新JSP后Datepicker无法正常工作的求助
Hey there, let's work through this Datepicker issue you're facing with dynamically loaded JSP content!
What's Likely Going On
The core problem here boils down to two common pitfalls with dynamic content and jQuery UI Datepicker:
- The
$(document).ready()block in your loaded JSP might not fire at all—since the main page'sdocumentalready finished loading before you injected the new content. - Datepicker uses a global container (
#ui-datepicker-div) by default. When you initialize a new Datepicker after loading content, it can clash with existing instances from the main page. Deleting that container fixes the new Datepicker but breaks the old ones because they rely on it.
Step-by-Step Fixes
1. Move Datepicker Initialization to the Load Callback
Instead of relying on $(document).ready() in your loaded JSP, initialize the Datepicker directly in the load() success callback—this ensures the new DOM elements exist before you try to bind the plugin.
Update your main JSP code to this:
$('#divNewJSP').load("myServlet?OP=1", function() { // Initialize the Datepicker here, after content is loaded $('#dateField').datepicker($.datepicker.regional["pt"]); $('#dateField').datepicker("show"); $('#divNewJSP').slideDown(); });
Then remove the $(document).ready() wrapper from your loaded JSP—you don't need it anymore, and it was probably not executing anyway.
2. Avoid Global Container Conflicts
To keep both the main page's Datepickers and the new one working, tell the dynamic Datepicker to use its own container instead of the global #ui-datepicker-div. Use the appendTo option to tie the popup to the loaded content's div:
$('#divNewJSP').load("myServlet?OP=1", function() { $('#dateField').datepicker({ ...$.datepicker.regional["pt"], appendTo: '#divNewJSP' // Confine the popup to the loaded div }); $('#dateField').datepicker("show"); $('#divNewJSP').slideDown(); });
This way, the new Datepicker's popup lives inside #divNewJSP and won't interfere with the main page's Datepicker instances.
3. Check for Duplicate Script Loads
Make sure your loaded JSP isn't re-including jQuery or jQuery UI. Re-loading these libraries will overwrite the existing jQuery object, breaking all previously initialized plugins (including your main page's Datepickers). Remove any duplicate <script> tags from the loaded JSP.
4. Clean Up When Removing Dynamic Content
If you ever need to hide or remove the loaded JSP content, destroy the Datepicker instance first to avoid leaving behind orphaned event handlers or DOM elements:
// Example: When closing the loaded div $('#divNewJSP').slideUp(function() { $('#dateField').datepicker("destroy"); // Clean up the instance $(this).empty(); // Clear the content });
Give these steps a try—adjusting the initialization timing and isolating the Datepicker container should resolve the conflict without breaking your main page's functionality.
内容的提问来源于stack exchange,提问作者D. Justo

