Javascript窗口函数加载

时间:2018-03-03 21:58:56

标签: javascript events addeventlistener getelementbyid

我有这个问题,我想用.innerHTML在div中加载一个文本但是在事件之后点击div diseapper里面的文本:

的index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Anagrafica</title>
    <link rel="stylesheet" href="css/style.css" />
</head>
<body>
    <h1>My Document</h1>

    <input type="submit" value="submit" id="submit">

    <div id="myDiv"></div>
    <script src="js/app.js"></script>
</body>
</html>

app.js

window.addEventListener('load',function(){      
  document.getElementById('submit').addEventListener('click',function({
      document.getElementById('myDiv').innerHTML= 'hello';
});

2 个答案:

答案 0 :(得分:0)

您有语法错误,)}缺失。

  

addEventListener('click',function({

看起来像回调,但你只需要附加function(){}。

 window.addEventListener('load',function(){      


   document.getElementById('submit').addEventListener('click', function(){
   
     document.getElementById('myDiv').innerHTML= 'hello';
     
   }, false);


 }, false);
<input type="submit" value="submit" id="submit">
<br/>
<br/>
<div id="myDiv" style="background-color:black;color:lime;width:300px" > ... </div>

答案 1 :(得分:0)

on html

<button type='submit'></button>

在js上

var Button = document.querySelector("button");

Button.addEventListener("click", onClickButton, false);
 function onClickButton(){

    // to do something here

  }