jquery: 解除对特定函数的绑定,保留其他函数。

问题描述 投票:0回答:1

我有一个简单的问题:我有两个不同的函数绑定到点击事件。

$("#selector").click(function one() {
// stuff
});

$("#selector").click(function two() {
// other stuff
});

我只想解除其中一个函数的绑定。我该怎么做呢?

jquery unbind
1个回答
2
投票

你需要将绑定的函数保存到变量中。之后你可以使用jQuery的.off()方法解除绑定。

(function($){

  var alert1 = function(){
    alert('1');
  }, alert2 = function(){
    alert('2');
  };
  
  // Bind alert1
  $('button').on('click',alert1);
  
  // Bind alert 2
  $('button').on('click',alert2);
  
  // Unbind alert2
  $('button').off('click',alert2);

})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button>Alert</button>

0
投票

这个 关闭功能 是你要找的

The .off() method removes event handlers that were attached with .on()

© www.soinside.com 2019 - 2024. All rights reserved.