2013-04-29 324 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