”Cannot read property ‘addEventListener’ of null“

1. error: cannot read property ‘addeventlistener’ of null

 

2. Solution:

put the code in window. Onload = function() {…}, because if the page has not been loaded into the BTN button and your code is placed in front of the BTN button, you call getelementbyid and the returned object is undefined

 

 

3. Window.onload usage details:

     The JavaScript script code in the web page often needs to be executed after the document is loaded. Otherwise, the object may not be obtained. To avoid this, you can use the following two methods:

1、 Put the script code at the bottom of the web page, so that when running the script code, you can ensure that the object to be operated has been loaded

2、 Execute the script code through window.onload. Window.onload is an event that will be triggered after the document is loaded. You can register an event handler for this event and put the script code to be executed in the event handler, so you can avoid the situation that the object cannot be obtained

 

4. Difference between document.ready and window.onload

In jQuery, we can see two ways to write: $(function () {}) and $(document). Ready (function () {})

After loading the document tree, the two methods are not the same (note that after loading the document tree, both of them have the same effect)

Window.onload executes a function after the DOM document tree is loaded and all files are loaded. In other words, $(document). Ready is executed before window.onload

Similar Posts: