简体   繁体   中英

How to make an onclick function work with jquery?

I'm new to Js and im having some issues with an onclick function. Ive added a button on HTML and then I wanted to make a popup window appear after clicking that button but I just can`t get it right on the js side.

Here are the codes:

HTML

<button class="boton1" onclick="mostrarMensaje()">
       <span class="popuptext1" id="myPopup1">Conector PS/2</span>
       <img src="./images/boton2.png" class="img1">
</button>

JS

$("#boton1").on("click", mostrarMensaje());

function mostrarMensaje() {
    $("#popuptext1").trigger("show");
}

Remove the onclick attribute from the HTML (See Why are inline event handler attributes a bad idea in modern semantic HTML? ) and change your JS code to:

$("#boton1").on("click", mostrarMensaje);

Your current code calls the function mostrarMensaje and passes the return value to .on , when you need to just pass the handler function as an argument to the .on function.

I'm not going to repeat what Shree said, see their answer for the explanations for the other issues.

Full Code:

 $(".boton1").on("click", mostrarMensaje); function mostrarMensaje() { $(".popuptext1").show(); }
 .popuptext1 { display: none; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="boton1"> <span class="popuptext1" id="myPopup1">Conector PS/2</span> <img src="./images/boton2.png" class="img1"> </button>

You already call mostrarMensaje() function on HTML <button class="boton1" onclick="mostrarMensaje()"> so no need to call it from jQuery. Hide your button text when it's load.Instead of trigger() , use show() to show your text on button click.

 function mostrarMensaje() { $(".popuptext1").show(); }
 .popuptext1 { display: none; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="boton1" onclick="mostrarMensaje()"> <span class="popuptext1" id="myPopup1">Conector PS/2</span> <img src="./images/boton2.png" class="img1"> </button>
Note: You are using # for class. Use . when using class.

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