在点击jQuery上绑定两个事件

jih*_*uNI 2 html javascript jquery

我想用一个按钮创建一个简单的用户交互,以开始和停止录制音频,例如whatsapp。我查看了stackoverflow来了解我是否写错了,因为我知道不可能在同一元素上绑定两个click事件,因此我决定在codepen上测试代码,但不会产生预期的结果:

$('#audioBtn').on('click' ,function(e){
  e.preventDefault();
  if( $(this).hasClass('active') ){
    $(this).removeClass('active')
    .addClass('inactive');
    console.log('Recording stopped');
  }
});

$('#audioBtn').on('click' , function(e){
  e.preventDefault();
  if( $(this).hasClass('inactive') ){
    $(this).addClass('active')
    .removeClass('inactive');
    console.log('Recording start');
  }
});

Run Code Online (Sandbox Code Playgroud)

发生的事情是两个事件同时在控制台上登录,但这不是我想要的,我只想使用相同的按钮来开始和停止录制,并在用户录制音频时更改图标。有什么办法吗?

Ror*_*san 6

我知道不可能将两个click事件绑定在同一元素上

事实并非如此,完全有可能将同一事件类型的多个事件处理程序绑定到单个元素。您遇到的问题是因为两个处理程序相互冲突;一个设置该类,另一个检测到该类并将其删除。

要解决此问题,您需要使用单个事件处理程序来检测元素的状态并根据该状态对其进行更新。在您的情况下,一个简单的else语句将起作用。

$('#audioBtn').on('click', function(e) {
  e.preventDefault();
  if ($(this).hasClass('active')) {
    $(this).removeClass('active').addClass('inactive');
    console.log('Recording stopped');
  } else {
    $(this).addClass('active').removeClass('inactive');
    console.log('Recording start');
  }
});
Run Code Online (Sandbox Code Playgroud)

更进一步,您可以toggleClass()用来交换类:

$('#audioBtn').on('click', function(e) {
  e.preventDefault();
  
  if ($(this).hasClass('active')) {
    console.log('Recording stopped');
  } else {
    console.log('Recording start');
  }
  
  $(this).toggleClass('active inactive');
});
Run Code Online (Sandbox Code Playgroud)
.active {
  color: #C00;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="audioBtn">Start/Stop</button>
Run Code Online (Sandbox Code Playgroud)