简体   繁体   English

JavaScript / jQuery-重用元素的事件“ Click”

[英]JavaScript/jQuery - Reusing the event 'Click' of an element

I have an element, a div, for example. 我有一个元素,例如div。 And attach an event 'click' to it. 并附加一个事件“单击”到它。 In jQuery, it would be: 在jQuery中,它将是:

 $('#myDiv').click(function(){ 
    $(".class1").show();
 })

Now, I would like to assign a new function "myDiv #", replacing the old. 现在,我想分配一个新函数“ myDiv#”,以替换旧函数。 I am doing so: 我正在这样做:

$('#myDiv').click(function(){ 
    $(".class23").hide();
})

But when I run the 'click' on the div, the function I assigns the beginning of this doubt is performed. 但是,当我在div上运行“单击”时,将执行我分配此疑问开头的函数。

Question: How to remove the function that will run with the click event attributed to an element? 问题:如何删除将归因于元素的click事件运行的功能? (No recreate the element with the new click event...) (不使用新的click事件重新创建元素...)

You want .unbind . 您需要.unbind

You can either remove all previous bound functions: 您可以删除所有以前的绑定函数:

$('#myDiv').unbind('click');

Or if you only want to unbind one specific function: 或者,如果您只想解除一个特定功能的绑定:

var show = function() { 
   $(".class1").show();
};

$('#myDiv').click(show);

and then: 接着:

$('#myDiv').unbind('click', show); // unbind first function

$('#myDiv').click(function() {     // bind second function
    $(".class23").hide();
});

Note that .click(func) is just a shortcut to .bind('click', func) . 请注意, .click(func)只是.bind('click', func)的快捷方式。

If you know you'll only want to handle one click on an element, you can use one() which automatically unbinds after a single click: 如果您只想处理元素的一次单击,则可以使用one() ,单击一次后自动解除绑定:

$("#myDiv").one("click", function() {  
  $(".class1").show();
  $("#myDiv").one("click", function(){ 
    $(".class23").hide();
  });
});

使用JQuery解除绑定功能删除所有单击事件

$('#myDiv').unbind('click');

Add a counter on the first click event. 在首次点击事件上添加一个计数器。

var counter = 0;
$('#myDiv').click(function(){ 
    if(counter>1){
       $(".class23").hide();
    }
    else
       $(".class1").show();

   counter++;
 })

just an example.. 只是一个例子

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

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