2012-02-21 101 views
-2

由於某些原因,我必須通過javascript函數分配javascript代碼,如下面的代碼。通過javascript函數分配javascript代碼

<html> 
    <head> 
    <script> 
     window.onload = init(); 
     function init(){ 

      document.getElementsByName('content')[0] = alert('LOL'); 

     } 
    </script> 
     <script type="text/javascript" name="content"> 


    </script> 
    </head> 
    <body> 

    </body> 
</html> 

頁面加載後,預期結果應該像下面

<html> 
    <head> 
    <script type="text/javascript"> 
     alert('LOL'); 

    </script> 
    </head> 
    <body> 

    </body> 
</html> 

然而,alertbox不顯示。有沒有人可以幫助我?

+2

爲什麼要這樣?你想要完成什麼? – Sjoerd 2012-02-21 15:47:07

+0

確定這裏真正發生了什麼? – Esailija 2012-02-21 15:47:38

+0

提高您的樣本質量,腳本標記和getElemen *** t *** sById中的錯誤。我們無法編輯這麼幾個字符... – 2012-02-21 15:49:17

回答

0

寫這個:

window.onload = function init(){ 
    document.getElementsByName('content')[0] = 'LOL'; 
    alert('LOL'); 
} 
0

只是改變了JavaScript代碼的文本不會讓它執行,因爲它是在客戶端。我會做更是這樣的:

window.onload = init(); 
    function init(){ 

     document.getElementsByName('content')[0] = function SomeMethod(){ alert('LOL'); }; 
     SomeMethod(); 
    } 
2

爲了讓你開始:

  • 不要拼錯腳本
  • 不要拼錯元素
  • 沒有爲腳本元素沒有name屬性
  • onload = foo()將立即調用foo並將其返回值分配給onload。擺脫()
  • 瀏覽器(AFAIK)不會重視對現有腳本元素的修改,只有新的腳本元素。所以請使用createElementappendChild