未从span调用onload

时间:2018-08-07 02:09:54

标签: javascript html

我的代码出现了一个非常初学者的错误。这是HTML:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv='content-type' content='text/html; charset=utf8' />
        <script type = 'text/javascript' src="scriptFirst.js"></script>
</head>
    <header>
        <span onLoad='textChange()' id='title' class='welcome'>

        </span>
        <nav class='welcome'>
        </nav>
        <br>
        <div id = 'firstDiv'>
        </div>
    </header>
</html>

这是我的JavaScript,名称为scriptFirst.js,与html位于同一文件夹中。

function textChange(){
var title = document.getElementById("title");
title.innerHTML = "hello";
alert('hello')
}

不幸的是,在浏览器中运行此代码会给我一个空白的屏幕。

1 个答案:

答案 0 :(得分:0)

将onload放在body元素中,然后将元素包装在其中。

<body onload="myFunction()"> your code here ... </body>

function textChange(){
var title = document.getElementById("title");
title.innerHTML = "hello";
alert('hello')
}
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv='content-type' content='text/html; charset=utf8' />
</head>
<body onload='textChange()'> 
<header>
        <span id='title' class='welcome'>

        </span>
        <nav class='welcome'>
        </nav>
        <br>
        <div id = 'firstDiv'>
        </div>
  </header>
  </body>
</html>

相关问题