简体   繁体   English

如何将onclick事件链接到JavaScript?

[英]How to link an onclick event to a javascript?

I am trying to link the following onclick function 我正在尝试链接以下onclick函数

 <body> <form action="/action_page.php"> Nombre o RUT:<br> <input type="text" name="firstname" value=" "> <button onclick="myFunction()">Click me</button> </form> <script type="text/javascript"> var myLink = document.getElementById('mylink'); myLink.onclick = function(){ var script = document.createElement("script"); script.type = "text/javascript"; script.src = "https://rutificadorcom.s3.amazonaws.com/CACHE/js/fdb8313f6402.js"; document.getElementsByTagName("head")[0].appendChild(script); return false; } </script> </body> 

To the js code published here: https://rutificadorcom.s3.amazonaws.com/CACHE/js/fdb8313f6402.js 此处发布的js代码: https : //rutificadorcom.s3.amazonaws.com/CACHE/js/fdb8313f6402.js

But I don't know why after clicking the button My search does not yield any results. 但是我不知道为什么在单击按钮后我的搜索没有任何结果。

I have already copied and pasted the js code in a local file on my computer to refer to it in my own machine. 我已经将js代码复制并粘贴到计算机上的本地文件中,以便在自己的计算机中引用它。 However, this action has not worked either. 但是,此操作也不起作用。

To "make a button do something when you click it" in your code just name the function you want to do as 'myFunction' (same name you putted on the onclick). 要在代码中“使按钮在单击时执行某些操作”,只需将要执行的函数命名为“ myFunction”(您在onclick上输入的相同名称)。

Your code fixed: 您的代码已修复:

<body>

<form action="/action_page.php">
Nombre o RUT:<br>
<input type="text" name="firstname" value=" ">
<button onclick="myFunction()">Click me</button>
</form>

<script type="text/javascript">

function myFunction() {
  alert("Hi!");
}

</script>

</body>

That works but, it would be better if you do this on a external js file and without the onclick. 那行得通,但是如果您在外部js文件上并且没有onclick的话,这样做会更好。

HTML: HTML:

<button id="alertButton">Click me</button>

JS: JS:

var buttonWithAlert = document.querySelector('#alertButton');

buttonWithAlert.addEventListener("click", function(){
    alert("Hi!");
});

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

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