jQuery.bind取消绑定,多个类实例 [英] jQuery.bind unbind, multiples instances of classes

查看:66
本文介绍了jQuery.bind取消绑定,多个类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个元素具有相同的可点击"类,我将所有这些类与以下各项绑定在一起:

I have multiple elements with the same class "clickable", i'm binding all these classes with:

 $('.clickable').bind('click', function()
     { 
       $(this.id).html('clicked');

     }

我假设绑定分别将每个元素与可单击"类绑定. 然后在此绑定函数中,我想将当前单击的元素与以下内容解除绑定:

I'm assuming the bind binds each element with the class "clickable" individually. Then within this bind-function, I want to unbind the currently clicked element with:

 $(this.id).unbind('click');

因此,如果您再次在此元素中单击,它将不会再次触发单击功能. 然后,在元素中做完所有事情之后(将这些元素与文本替换为,将当前文本放入其中,当您在其外部单击时,它将更改其html),我想再次重新绑定该点击,但是我似乎无法取消对此this.id的点击绑定...

So that if you click again within this element, it doesn't trigger the click-function again. And then, after doing stuff within the element (replace the text withing these elements with an that puts the current text in it, and when you click outside it it wil alter the html for it) I want to rebind the click again, but I cant't seem to unbind the click for this.id...

一些小提琴需要澄清: http://jsfiddle.net/TrySpace/QZMP6/7/

Some fiddle for clarification: http://jsfiddle.net/TrySpace/QZMP6/7/

推荐答案

可能是因为您的选择器错误(因为当您真正想要$("#my_id")时,选择器将转换为类似$("my_id")的名称).在这种情况下,您可以这样做:

Probably because your selector is wrong (because your selector would translate to something like $("my_id") when you really want $("#my_id")). In this case, you could just do:

$(this).unbind('click');

从根本上说,这比再次向DOM查询元素要好.

Which is ultimately better than querying the DOM again for an element.

旁注:从jQuery 1.7开始不推荐使用bindunbind.编写此代码的更新方法是使用onoff:

Side note: bind and unbind are deprecated as of jQuery 1.7. The updated way to write this is with on and off:

$(".clickable").on("click", function () {
    /* ... */
    $(this).off("click");
});

编辑(以下评论):

如果您还希望阻止通知父事件处理程序,则可以绑定一个新的处理程序,以防止事件的传播:

If you want to prevent parent event handlers from being notified as well, you could bind a new handler that prevents propagation of the event:

$(this).off("click").on("click", function (e) {
    e.stopPropagation();
});

这篇关于jQuery.bind取消绑定,多个类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆