2013-04-29 325 views
0

为什么消息框不显示?非常感谢。将JS添加到body元素

<!DOCTYPE html> 
<html> 
<head> 
    <script src="jquery-1.8.0.min.js" type="text/javascript"></script> 
    <script type="text/javascript"> 
     $('<script>alert("hi");</' + 'script>').appendTo(document.body); 
    </script> 
</head> 
<body> 
    <span>my test</span> 
</body> 
</html> 
+0

你真的想完成什么?脚本通常会附加到head元素,而不是body元素来完成动态加载,通常您会创建一个脚本元素并指定一个'.src' URL,然后将其附加到head元素。 – jfriend00 2013-04-29 15:52:00

+0

脚本可以在头部或身体中,我不认为它有所作为。 – Barmar 2013-04-29 15:56:37

+0

好吧,我有一个CMS的问题,它添加了“addthis.com”javascript到错误设置的页面。该脚本位于body元素中,我需要将另一个脚本附加到body元素的末尾,这将更改脚本属性之一。解决方案在这里解释:http://support.addthis.com/customer/portal/questions/352733-how-to-remove-hash-from-url-,不幸的是,当我使用$(文档).ready()函数。 – lekso 2013-04-29 16:04:16

回答

3

您必须包装在$(document).ready

否则它将无法找到body,因为它尚未加载。

$(document).ready(function() { 
    $('<script>alert("hi");</' + 'script>').appendTo(document.body); 
}) 
+0

谢谢。我将其标记为解决方案,尽管我的问题仍未解决。你可以看看这里:http://stackoverflow.com/questions/16283707/addthis-ads-a-hashtag-and-id-to-url-how-to-remove-it – lekso 2013-04-29 16:32:38