简体   繁体   English

Javascript在html文件中不起作用

[英]Javascript doesn't work in html file

I have html file: 我有html文件:

<html>
  <head>
    <script type="text/javascript" src="new.js"></script>

  </head>
  <body>
    <p id="contentBI" >you should click here! </p>
  </body>
</html>

and javascript file: 和javascript文件:

function doAlert() {
  alert("hi!");
}

function addevent () {
  theBI=document.getElementById("contentBI");
  theBI.addEventListener("click",doAlert);
}

document.addEventListener("load",addevent);

Javascript doesn't run. JavaScript无法运行。

use window.addEventListener("load",addevent); 使用window.addEventListener("load",addevent); instead of document.addEventListener("load",addevent); 而不是document.addEventListener("load",addevent);
DEMO 演示

So you want a document ready like jquery, try this: 因此,您希望像jquery一样准备好文档,请尝试以下操作:

document.addEventListener("DOMContentloaded",addevent, false);

Demo here 在这里演示

Assuming this is all of your code, the first issue you should tackle is telling your page where your Javascript is at. 假设这是所有代码,那么您应该解决的第一个问题就是告诉页面Javascript的位置。

Try placing your script between <script> </script> tags within your HTML file. 尝试将脚本放在HTML文件中的<script> </script>标记之间。

</head>
<body>


<p id="contentBI" >you should click here! </p>


<script>
function addevent (){

theBI=document.getElementById("contentBI");
theBI.addEventListener("click",doAlert);
}
document.addEventListener("load",addevent);
</script>  


</body>
</html
  • It still won't work, most likely. 它仍然可能无法正常工作。 But it's a start. 但这是一个开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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