简体   繁体   English

如何使用相同的按钮实现两种不同的行为

[英]How to achieve two different behaviors with the same button

I created a click event, which changes the identifier of a button. 我创建了一个click事件,它更改了按钮的标识符。 I created a second click event on the same button but this time with the new id. 我在同一个按钮上创建了第二次单击事件,但这次使用了新的id。 When I click the button, a second time. 当我第二次点击按钮时。 I always have the first behavior with the old id. 我总是有旧id的第一个行为。 Here is the code to better illustrate this example. 以下是更好地说明此示例的代码。 The idea is to do two different behaviors with the same button 我们的想法是使用相同的按钮执行两种不同的行为

$('#button').on('click',function () {
    $(this).attr('id','buttonBis');
});

$('#buttonBis').on('click',function () {
    alert('here');
});

If you're changing the identifiers dynamically then you will need to use delegated event handlers: 如果要动态更改标识符,则需要使用委派的事件处理程序:

 $(document).on('click', '#button', function() { $(this).attr('id', 'buttonBis'); }); $(document).on('click', '#buttonBis', function() { alert('here'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="button">Click me twice to see the alert()</button> 

Note that dynamically changing id attributes is not considered a very good idea, and should avoided where possible. 请注意,动态更改id属性不是一个好主意,应该尽可能避免。 I'd suggest adding/removing classes would be a much better alternative. 我建议添加/删除类是一个更好的选择。

Create function to assign event to new button id and remove attached (prevent duplication of) event by replacing the dom node by its colne , 创建函数以将事件分配给新按钮ID并通过用其colne替换dom节点来删除附加(防止重复)事件,

 $('#button').on('click',function () { $(this).attr('id','buttonBis'); //clone the node then reissign to the same node // which removes the previous attached events var self = this.cloneNode(true); $(this).replaceWith(self); newevent(); }); var newevent = function() { $('#buttonBis').on('click',function () { alert('here'); }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="button" >Click Me twice </button> 

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

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