如何用jQuery将内容加载到上级页面的指定div中?
Question:
I'm using this simple jQuery code to load content into a div on my current page, and it works fine:
$(document).ready(function() { // INITIAL "use strict"; $('#box-03').load('EXTREL_CONTENT/2up.php'); // Handle menu clicks $('ul#main-menu li a').click(function() { var page = $(this).attr('href'); $('#box-03').load('EXTREL_CONTENT/' + page + '.php'); return false; }); });
Can I load the same content into the #box-4 div that's located in another PHP page in the parent directory?
Answer:
Absolutely, but there are a few key constraints and workarounds to keep in mind—let’s break this down:
Direct cross-page manipulation isn’t possible
First, a quick reality check: your current jQuery code runs in the context of the page it’s loaded in. Browsers restrict JavaScript to only modifying the DOM of the currently active page, so you can’t directly reach into an unrelated page in the parent directory and update its#box-4div.Two practical solutions depending on your setup
If the target page is a parent iframe
If your current page is embedded inside the parent directory’s page via an iframe, you can use theparentobject to access the parent page’s DOM. Modify your code like this:$(document).ready(function() { "use strict"; // Load content into the parent page's #box-4 parent.$('#box-4').load('EXTREL_CONTENT/2up.php'); // Handle menu clicks to load into parent's #box-4 $('ul#main-menu li a').click(function() { var page = $(this).attr('href'); parent.$('#box-4').load('EXTREL_CONTENT/' + page + '.php'); return false; }); });Important note: This only works if both pages are hosted on the same domain—browser cross-origin security rules block this otherwise.
If the target page is a standalone page
If the parent directory’s page is a separate, independently loaded page, you can’t modify it directly from your current page. Instead, try these approaches:- Pass a URL parameter to the target page (e.g.,
../parent-page.php?load=2up), then add code to the parent page that reads this parameter and loads the corresponding content into#box-4on page load. - Use
localStorageorsessionStorageto store the name of the content to load. Add a listener to the parent page that watches for changes to this storage value, then triggers theload()function when a change is detected.
- Pass a URL parameter to the target page (e.g.,
Double-check file paths
Make sure the path to yourEXTREL_CONTENT/xxx.phpfiles is valid from the context of the target page. If the target page is in the parent directory, you might need to adjust the path to./EXTREL_CONTENT/xxx.php(or whatever relative path points correctly to the content folder) to avoid 404 errors.
内容的提问来源于stack exchange,提问作者Biociek Klekocinski

