This loaded page contains a script that I want to execute when it has
finished loading. I've put together a simple example to demonstrate:
Index.html:
<html>
<head>
<title>Jquery Test</title>
<script type="text/javascript" src="script/jquery-1.3.2.min.js"></
script>
<script type="text/javascript">
$(document).ready(function()
{
$('#nav a').click(function()
{
$('#contentHolder').load('content.html #toLoad', '', function
() {});
return false;
});
});
</script>
</head>
<body>
<div id="nav">
<a href="content.html">Click me!</a>
</div>
<hr />
<div id="contentHolder">
Content loaded will go here
</div>
</body>
</html>
Content.html:
<div id="toLoad">
This content is from content.html
<div id="contentDiv">
This should fade away.
</div>
<script type="text/javascript">
$('#contentDiv').fadeOut('slow', function() {} );
</script>
</div>
When the link is clicked, the content should load and the second
paragraph should fade away. However it doesn't execute. It is not just
a matter of the DOM not being available, a simple alert("") won't
execute either.
However, if I do away with the #toLoad selector in the .load() call,
it works fine. I am not sure why this is, as the <script> block is
clearly in the scope of the #toLoad div?
Any ideas? If the script from content.html was in the .load()
callback, it works fine.
I have worked around the problem by having the callback use .getScript
() to load "content.js" afterwards and have the JS logic in there.
This is arguably a more elegant solution anyway, but I'm keen to know
*why* the above doesn't work, is it a bug?
Thanks!
No comments:
Post a Comment