2015-06-14 83 views
2

我想点击按钮时触发一些JavaScript代码。 我想要点击按钮时console.log()被触发。 我尝试:点击触发JavaScript动作?

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'); 
} 

我不明白什么不起作用?

+0

这很好,您的控制台上有错误? –

+0

控制台中是否有任何错误? –

+0

确保您的JavaScript文件的引用也是正确的。 – Dummy

回答

2

该按钮使得表单提交,因此你需要使用的preventDefault()

See this demo

使用此代码,

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(); 
} 
+0

请注意,OP有他的JS代码在一个单独的文件('corel.js')。这将是一个很好的证明他如何在一个内联的JS文件中实现这个解决方案。 –

+0

@jsve感谢您指出并更新了它 –

0

尝试也:

<button onclick="return myFunction()">Click me</button> 
function myFunction() { 
    console.log('yeah'); 
    return false 
} 
1

单击按钮刷新页面。如果你打开控制台并选择保存日志,你会看到它的工作原理。

如果你不想刷新,那么你需要一个回添加到您的函数是这样的:

function myFunction() { 
    console.log('yeah'); 
    return false; 
} 

并在您的HTML按钮的代码应该如下:

<button onclick="return myFunction()">Click me</button> 

参考: prevent refresh of page when button inside form clicked