我发现很多关于这个主题的例子。但是,我不完全理解。 请问我的逻辑似乎正确吗? 我有一个div的按钮(类.myClass的),我不希望它点击除非mycount的> = 1。
// I want to unbind if myCount == 0
if ( myCount == 0) {
$('.myClass').unbind().css("opacity","0.5");
} else {
// **would this rebind?**
$('.myClass').click(callMyFunction);
}
你可以使用命名空间的事件, on()
bind()
已被弃用。
var foo = function () { ... }
if (myCount)
$('.myclass').on('click.foo', foo)
else
$('.myclass').off('.foo')
我不知道你想要什么来实现的,但.unbind()
时不带参数调用除去附着在单元的所有处理。 因此, $('.myClass').unbind()
除去附着于一类的元素的所有事件处理程序.myClass
。 既然你只能似乎是增加一个事件处理程序, click
,倒不如只取消绑定click
处理,像这样: $('.myClass').unbind('click')
这样,为什么,如果你添加额外的事件以后其他事件正在unbinded你不会被迷惑。
click(callMyFunction)
is shorthand for .bind("click", callMyFunction)
or .on("click", callMyFunction)
.
To bind use on()
to unbind use off()
. Those are the preferred methods since jQuery 1.7. If you are using an older version use bind()
, unbind()
, or delegate()
and undelegate()
$('.myClass').off('click')
and to bind
$('.myClass').on('click', function(){});
As mentioned in another post, using namespaces is an additional way to categorize your events such as click.mynamespace
for example.
See this post for much more detail on the different available binding methods and which were introduced when and have replaced what and why.
Some more resources:
- click()
- unbind()
- on()
- off()