2017-02-28 15 views
0

我是javaScript的新手,並且正在通過將回調函數連接到事件的各種技術。將回調函數連接到onload事件以便正文元素失敗

在從html中分離出所有JS代碼並且連接window.onload塊中的所有回調函數的技術(Head First JavaScript強烈推薦,我遵循該方法)時,onload事件的body元素的接線不起作用。

我期待2個警告框,被跟隨Hii其他與Hello(當我點擊的按鈕),但我只讓你好(通過點擊按鈕),但在此之前,我沒有得到Hii警告框。

<!DOCTYPE html> 
<html> 
<head> 
    <title>Test</title> 
    <script type="text/javascript"> 
     function fun1() { 
      alert("Hii"); 
     } 

     function fun2() { 
      alert("hello"); 
     } 

     window.onload = function() { 
      document.getElementsByTagName('body')[0].onload = function() { 
       fun1(); 
      }; 

      document.getElementById('btn1').onclick = function() { 
       fun2(); 
      }; 
     }; 
    </script> 
</head> 
<body> 
    <input type="button" id="btn1" value="Click"> 
</body> 
</html> 

問題的第二部分;

在下面的代碼,我謹onloadbody元素的HTML代碼本身,然後我得到Hii只有一個警告框(如預期),但隨後由於預期onlick事件上的按鈕不起作用,其警戒框Hello

<!DOCTYPE html> 
<html> 
<head> 
    <title>Test</title> 
    <script type="text/javascript"> 
     function fun1() { 
      alert("Hii"); 
     } 

     function fun2() { 
      alert("hello"); 
     } 

     window.onload = function() { 
      document.getElementById('btn1').onclick = function() { 
       fun2(); 
      }; 
     }; 
    </script> 
</head> 
<body onload="fun1()";> 
    <input type="button" id="btn1" value="Click"> 
</body> 
</html> 

這種不確定的行爲困擾着我。

回答

1

window.onload的問題是它在body.onload事件之後觸發。這就解釋了爲什麼從未調用fun1:在您將onload事件處理程序附加到body標記時,在將處理程序附加到它之前,該事件已被觸發。

改進此問題的一種方法是聽DOMContentLoaded事件。它會在body.onload事件之前觸發。實際上,當您確實需要整個文檔內容(包括要加載的圖像)時,您只需要使用window.onloadDOMContentLoaded將在此之前觸發 - 當DOM樹可用時。

所以這應該工作:

document.addEventListener('DOMContentLoaded', function() { 
    document.body.onload = function() { 
     fun1(); 
    }; 

    document.getElementById('btn1').onclick = function() { 
     fun2(); 
    }; 
}); 

但實在沒有理由有一個單獨的body.onload處理程序。你不妨這樣做:

document.addEventListener('DOMContentLoaded', function() { 
    fun1(); // call it when the DOM content is loaded. 

    document.getElementById('btn1').onclick = function() { 
     fun2(); 
    }; 
}); 

而且,......它是分配事件處理程序與addEventListener最佳做法,因爲它允許附加多個處理程序相同的事件,所以不同的腳本沒有在這方面與海誓山盟干擾:

document.addEventListener('DOMContentLoaded', function() { 
    fun1(); // call it when the DOM content is loaded. 

    document.getElementById('btn1').addEventListener('click', function() { 
     fun2(); 
    }); 
}); 

當您在事件處理程序中執行只是一個函數的捷徑可應用於:不是包裹在一個匿名函數中調用,你還不如傳遞函數本身作爲參考:

document.addEventListener('DOMContentLoaded', function() { 
    fun1(); // call it when the DOM content is loaded. 

    document.getElementById('btn1').addEventListener('click', fun2); 
});