简体   繁体   中英

How to link an onclick event to a javascript?

I am trying to link the following onclick function

 <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

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. 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).

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.

HTML:

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

JS:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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