[英]how to I get a html button to work with a java script function?
I have a button in a html file with that when clicked should run a function in a java script file that send an alert that says hey.我在 html 文件中有一个按钮,单击该按钮时应该在 java 脚本文件中运行一个函数,该函数会发送一个警报,说嘿。 This doesn't happen and I don' know why.
这不会发生,我不知道为什么。 It feels like the simplest thin but I just can't get it to work.
感觉就像最简单的瘦,但我就是无法让它发挥作用。 Java Script is enabled in my browser (google chrome) I don't think it matters but just in case, I'm codeing in VS code.
在我的浏览器(谷歌浏览器)中启用了 Java Script 我认为这并不重要,但以防万一,我在 VS 代码中进行编码。
function myfunction() { alert("hey"); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="script.js" type="module"></script> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div id="head"> <h1>Park Stats</h1> </div> <table> <tr id="head_row"> <th>Player</th> <th>Points</th> <th>Rebounds</th> <th>Blocks</th> <th>Steals</th> <th>Fouls</th> <th>Scrum Wins</th> <th>Scrum Losses</th> <th>Assists</th> </tr> <tr> <td>Player Name<button class="name_button">✎</button></td> <td> <div class="container"> <button>-</button> <div id="p1s1" class="stat">0</div> **<button onclick="myfunction();">+</button>** </div> </td> </tr> </table> </body> </html>
If you are using your code local and not on a webserver you have to remove the attribute type="module" .如果您在本地而不是在网络服务器上使用代码,则必须删除属性type="module" 。 see: javascript modules and CORS
请参阅: javascript 模块和 CORS
and MDN JavaScript modules和MDN JavaScript 模块
Change this改变这个
<script src="script.js" type="module"></script>
To至
<script src="script.js"></script>
And now it works for me.现在它对我有用。
**<button onclick="myfunction();">+</button>**
应该是**<button id="alert-button">+</button>**
document.addEventListener('DOMContentLoaded', (event) => { document.getElementById("alert-button").addEventListener('click', function(){ myFunction(); }) });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.