为什么控制台返回“TypeError:newIndustry为null”?

时间:2013-12-11 02:58:26

标签: javascript

当我到达这条线时,有没有人看到出了什么问题......

    newIndustry.innerHTML = industryNews[generateRandomNumber()-1]
}

这是我的源码js(我只是将文本放到带有#industryNews的h1中)

var industryNews = [];
industryNews[0] = "Lorem ipsum dolor <strong>sit</strong> amet, consectetur adipisicing elit. Optio, ut, maxime, eum, fugit dolor nulla cupiditate beatae sapiente dignissimos accusamus cumque fuga alias accusantium praesentium nisi placeat quam ad eius.";
industryNews[1] = "Lorem ipsum dolor <strong>sit</strong> amet, consectetur adipisicing elit. Provident, consequuntur, officia veritatis molestias odio nobis minima iste id tenetur possimus magni nisi error enim minus aperiam? Minus, iure delectus cumque.";
industryNews[2] = "Lorem ipsum dolor <strong>sit</strong> amet, consectetur adipisicing elit. Sint, in, qui voluptatibus voluptas inventore recusandae non quos adipisci dolor beatae dolore saepe quaerat exercitationem dolores delectus quo pariatur. Quae, quidem.";
industryNews[3] = "Lorem ipsum dolor <strong>sit</strong> amet, consectetur adipisicing elit. Assumenda, sed, laborum, quisquam rerum quo non aspernatur necessitatibus soluta id debitis impedit corporis magnam praesentium ab odit dicta aperiam autem consequuntur!";

var newIndustry = document.getElementById("industryNews");

// generate a # between 1 &4
function generateRandomNumber(){
    return Math.floor(Math.random()*(4)+1);
}

function updateindustryNews () {
    // var interval = generateRandomNumber();
    newIndustry.innerHTML = industryNews[generateRandomNumber()-1]
}

updateindustryNews();

setInterval(updateindustryNews,4000);

1 个答案:

答案 0 :(得分:1)

在HTML存在之前,您无法在页面上document.getElementById()。因此,您的脚本标记必须位于您的身体底部或头部。如果在您的脑海中,您必须使用onload这是window的属性,这是隐含的。

此外,与您的问题无关,但Math.random()会返回介于0和.9之间的数字,而不是1,所以

function generateRandomNumber(){
  return Math.floor(Math.random()*(4)+1);
}

是一个蹩脚的公式,因为Math.floor(0.99999*4+1) = 4.应该是:

function generateRandomNumber(){
  return Math.floor(Math.random()*4);
}

现在你不必-1。