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

Kub*_*hon 3 javascript jquery

我创建了一个click事件,它更改了按钮的标识符.我在同一个按钮上创建了第二次单击事件,但这次使用了新的id.当我第二次点击按钮时.我总是有旧id的第一个行为.以下是更好地说明此示例的代码.我们的想法是使用相同的按钮执行两种不同的行为

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

$('#buttonBis').on('click',function () {
    alert('here');
});
Run Code Online (Sandbox Code Playgroud)

Ror*_*san 6

如果要动态更改标识符,则需要使用委派的事件处理程序:

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

$(document).on('click', '#buttonBis', function() {
  alert('here');
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

请注意,动态更改id属性不是一个好主意,应尽可能避免.我建议添加/删除类是一个更好的选择.