[英]Trigger javascript action on click?
我想在單擊按鈕時觸發一些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();
}
單擊按鈕刷新頁面。 如果打開控制台並選擇保留日志,您將看到它可以正常工作。
如果您不想刷新,則需要向函數添加如下所示的返回值:
function myFunction() {
console.log('yeah');
return false;
}
在您的html上,按鈕代碼應如下所示:
<button onclick="return myFunction()">Click me</button>
參考: 防止在單擊表單內的按鈕時刷新頁面
也嘗試:
<button onclick="return myFunction()">Click me</button>
function myFunction() {
console.log('yeah');
return false
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.