문제

var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'http://www.mydomain.com/bleh.php';
script.id = 'rawr';
$('head').append(script);
alert($('#rawr').attr('src'));

That returns null. Why is this?

도움이 되었습니까?

해결책

You can use the regular .appendChild() instead:

$('head')[0].appendChild(script);

http://jsfiddle.net/PeaqH/

What this will do is access the first <head> element on the page and then use the regular DOM child append. As far as why the method you tried didn't work, I'm not sure... I have to think about it, although I suspect it has something to do with how jQuery handles adding script elements to the page.

다른 팁

Why not use getScript?

Something worth looking into. Run this with Firebug open.

<script src="jquery.js" id="jq"></script>
<title>Untitled Document</title>

</head>

<body>
<div id="container"></div>
<script type="text/javascript">
$(function(){
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js';
script.id = 'rawr';

$('head').append(script);
console.log($('#jq'));
});
</script>

U will see that jqueryUI is not being shown in HTML tab of firebug but when u look at the Net tab its showing that jQueryui.min file has loaded. Now click on the console tab and expand #jq item. You can see all the options available to you. There is no src or source option. Hope this helped.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top