我想在单击按钮时触发一些 JavaScript 代码。
我希望当单击按钮时触发 console.log()
。
我的尝试:
corel.html:
<!DOCTYPE html>
<html>
<head>
<title>Corelation</title>
<script src="jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="corel.js"></script>
</head>
<body>
<form id="tableVar">
Variable 1: <input type="text" id="var1"><br>
Variable 2: <input type="text" id="var2"><br>
<button onclick="myFunction()">Click me</button> <!-- type is button to not refresh -->
</form>
</body>
</html>
corel.js:
console.log("iniating app ...");
function myFunction() {
console.log('yeah');
}
我不明白什么不起作用?
最佳答案
该按钮正在使表单提交,因此您需要使用 PreventDefault()
使用此代码,
HTML
<!DOCTYPE html>
<html>
<head>
<title>Corelation</title>
<script src="jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="corel.js"></script>
</head>
<body>
<form id="tableVar">
Variable 1: <input type="text" id="var1"><br>
Variable 2: <input type="text" id="var2"><br>
<button onclick="myFunction(event)">Click me</button> <!-- type is button to not refresh -->
</form>
</body>
</html>
Corel.js
console.log("iniating app ...");
function myFunction(event) {
console.log('yeah');
event.preventDefault();
}
关于javascript - 单击时触发 JavaScript 操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30825001/