簡體   English   中英

在頁面加載時執行JavaScript,但在單擊按鈕時不執行

[英]Execute javascript on page load but not on button click

嘗試了幾次以使其低於Javscript才能在頁面加載時執行。 當前,僅在單擊“開始”按鈕時有效。

如何使頁面加載變得激動?

<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(“ test”)。setProperty是將變量傳遞到SWF文件的函數。 在頁面加載時,我希望它得到執行,而不是單擊按鈕。

要使您的函數在頁面加載時執行,請提供以下代碼:

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

嘗試這個:

<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>

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

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

您可以做的是:

<body onload="start();">

如果您考慮完全使用jQuery,則可以將代碼包裝在以下內容中:

$(document).ready(function(){

      //the code

});

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

采用:

(function($){

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

})(jQuery)

使用window.onload事件在加載時觸發代碼。


window.onload = function(){

//your code to execute
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM