[英]How to make an onclick function work with jquery?
I'm new to Js and im having some issues with an onclick function.我是 Js 新手,我对 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.
我在 HTML 上添加了一个按钮,然后我想在单击该按钮后弹出一个 window ,但我无法在 js 端正确显示它。
Here are the codes:以下是代码:
HTML HTML
<button class="boton1" onclick="mostrarMensaje()">
<span class="popuptext1" id="myPopup1">Conector PS/2</span>
<img src="./images/boton2.png" class="img1">
</button>
JS 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:从 HTML 中删除
onclick
属性(请参阅为什么内联事件处理程序属性在现代语义 HTML 中是一个坏主意? )并将您的 JS 代码更改为:
$("#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.您当前的代码调用 function
mostrarMensaje
并将返回值传递给.on
,此时您只需将处理程序 function 作为参数传递给.on
。
I'm not going to repeat what Shree said, see their answer for the explanations for the other issues.我不会重复 Shree 所说的话,请参阅他们对其他问题的解释的答案。
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.您已经在 HTML
<button class="boton1" onclick="mostrarMensaje()">
上调用了mostrarMensaje()
function,因此无需从 ZF590B4FDA2C30BE27777C8C3CAFCAF5 调用它。 Hide your button text when it's load.Instead of trigger()
, use show()
to show your text on button click.加载时隐藏按钮文本。而不是
trigger()
,使用show()
在按钮单击时显示文本。
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>
#
for class.
#
表示 class。
Use .
.
when using class.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.