jQuery: append div containing javascript files?
I am using jQuery 1.4 and I am trying to append DIVs that contain javascript files from another domain. I have the following inline code at the end of the body, just after loading jQuery:
<script src="jquery-1.4.3.min.js">&l开发者_运维百科t;/script>
<script src="scripts.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
var html = "<div><script type='text/javascript' src='http://example.com/foo'></script></div>";
$("#container").append(html);´
});
</script>
The problem is that the output is:
"; $("#container").append(html); } });
and it is not even displayed in #container but at the bottom of the body where the javascript code is.
EDIT: the javascript file inserts html for ads, so it cannot be loaded into the document head.
Dynamic script loading isn't possible using the method you describe as the string is loaded as HTML and not parsed. Try this:
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://example.com/foo';
head.appendChild(script);
Script tags with type "text/javascript" are being interpreted by the browser and not displayed. There's no logical reason to put a script tag into a div and hope it will display its content.
If you want scripts loaded from another domain, simply append those to the body not wrapping them in other tags. Once these files are loaded and run they might have code in them that appends something to your div#container element (note: I said might).
You need to first get the concept of DOM and scripting right, then ask again. I'll be glad to help you out.
Regards, aefxx
精彩评论