2012-03-15 81 views
0

嘗試多次以低於Javscript以在頁面加載時執行。目前僅在點擊「開始」按鈕時才起作用。在頁面加載時執行javascript,但不在按鈕上點擊

在頁面加載時如何激發它?

<script type="text/javascript"> 
function getFlashMovie(movieName) { 
    var isIE = navigator.appName.indexOf("Microsoft") != -1; 
    return (isIE) ? window[movieName] : document[movieName]; 
} 
function start() { 

    var active = document.getElementById("buttonstart").value == "stop"; 
    getFlashMovie("test").setProperty("src", !active ? document.getElementById('url2').value: null); 
    document.getElementById("start").value = active ? "buttonstart" : "buttonstop"; 
} 
</script> 

在html

<input id="url2" type="text" value="rtmp://localhost/?streammovie=test"/> 

的getFlashMovie( 「測試」)。的setProperty是通過可變SWF文件的功能。 頁面加載我希望它被執行,而不是點擊按鈕。

回答

1

你可以做的是:

<body onload="start();"> 

如果你考慮使用jQuery在所有的,那麼你可以內包代碼:

$(document).ready(function(){ 

     //the code 

}); 

當頁面有代碼將執行已完全加載,但我不建議添加jquery庫,以便您可以使用此功能。

+0

好吧那樣,但..然後你仍然需要點擊按鈕,啓動功能本身不會啓動set屬性只有當按鈕被點擊。 – Rubytastic 2012-03-15 08:31:12

0

用途:

(function($){ 

$(function(){ 
// my code comes here 
});  

})(jQuery) 
1

試試這個:

<script type="text/javascript"> 
function getFlashMovie(movieName) { 
    var isIE = navigator.appName.indexOf("Microsoft") != -1; 
    return (isIE) ? window[movieName] : document[movieName]; 
} 
function start() { 

    var active = document.getElementById("buttonstart").value == "stop"; 
    getFlashMovie("test").setProperty("src", !active ? document.getElementById('url2').value: null); 
    document.getElementById("start").value = active ? "buttonstart" : "buttonstop"; 
} 
start(); //added this 
</script> 
+1

如果腳本位於''部分,它將不起作用,因爲這些元素還不存在。 – 2012-03-15 08:24:34

+0

只需將其放在頁腳中,然後貼在身上。 – alykhalid 2012-03-15 08:25:24

+0

爲什麼在使用'window.onload'時強制這樣的事情? – 2012-03-15 08:29:23

2

要對頁面加載你的函數執行有這樣的代碼:

window.onload = function() { 
    start(); 
}; 
1

只需確保DOM已經加載在嘗試訪問任何元素之前。 嘗試在HTML末尾運行你的start()函數,就像這樣;

</body> 
    <script type="text/javascript"> 
    start(); 
    </script> 
</html> 
+0

好吧那樣,但..然後你仍然需要點擊按鈕,啓動功能本身不會啓動set屬性只有當按鈕被點擊。 – Rubytastic 2012-03-15 08:31:17

0

使用window.onload事件來加載您的代碼。

 

window.onload = function(){ 

//your code to execute 
} 

 
相關問題