简体   繁体   中英

Uncaught TypeError: Cannot read property 'style' of null?

I am struggling to figure out what is creating this error

My code is simple:

HTML:

<div id="bg">nsnsn</div>

Javascript:

function rSizer(){
    var bg = document.getElementById('bg');
    alert(bg.innerHTML); //error occurs on this line
}
document.ready(rSizer());
window.on('resize', rSizer());

I think instead of document.ready(rSizer()); you meant document.ready(rSizer); .

fiddle: http://jsfiddle.net/ad119d6h/2/

HTML

<div id="bg">nsnsn</div>

JS

function rSizer(){
    var bg = document.getElementById('bg');
    console.log(bg.innerHTML); //error occurs on this line
}
$(document).ready(rSizer);
$(window).on('resize',rSizer);

Works fine for me (told ya to change that document and window ;)

also, what Chris said..


UPDATE (pure JS no jquery)

fiddle: http://jsfiddle.net/ad119d6h/5/

window.onload = rSizer;
window.onresize = rSizer;

(the rest is the same)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM