简体   繁体   English

如何使用JavaScript更改动态HTML按钮的onClick事件

[英]How to change dynamic HTML button onClick event with Javascript

I have codes : 我有代码:

HTML : HTML:

<div class="modal-footer" >
     <button type="button" class="btn btn-sm btn-default" id="mybutton" style="background-color: #367E2D; color:white; opacity: 1" onclick="chooseme();">OK</button>
</div>

Javascript : Javascript:

('#mybutton').click(chooseme('123'));

Purpose : 目的:

I want to change onClick event from chooseme() to chooseme('123') using Javascript 我想使用Javascript将onClick事件从chooseme()更改为chooseme('123')

And the result of the code above is : 上面代码的结果是:

chooseme('123') executed immediately (not when the button clicked) selectme('123')立即执行(不单击按钮时)

Question is : Anyone can explain what's wrong with my code? 问题是:任何人都可以解释我的代码有什么问题吗? and what is the correct implementation to reach the purpose above? 达到上述目的的正确实现是什么?

I assume from the syntax that you're using jQuery. 我从语法上假设您正在使用jQuery。 When binding events to named functions in JS, you need to pass the function itself to the callback. 将事件绑定到JS中的命名函数时,您需要将函数本身传递给回调。 With your current syntax, you're passing the return value from chooseme() to the click handler. 使用当前语法,您chooseme() 返回值chooseme()传递给click处理程序。 As a result, the function is called immediately on page load. 结果,该函数在页面加载时立即被调用。

Wrap the hander inside an anonymous function, and you're good to go: 将hander包装在一个匿名函数中,您可以执行以下操作:

$('#mybutton').on('click', function() { chooseme('123') });

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

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