I've a "problem" with .live() and .die() methods. I'm using jQuery 1.5.1. Here is my scenario
<div id='div1' class='MyClass'>Link 1</div>
<div id='div2' class='MyClass'>Link 2</div>
<div id='div3' class='MyClass'>Link 3</div>
and my jQuery script
$('.MyClass').live('click', function(evt) {
local.href = 'home.aspx'
});
for some reason I want to disable Link 2 so I've tried to do this
$('#div2').die('click');
but it doesn't seem to works fine. I think that if I add an event using class selector I can't remove the same event using id selector. I must use .live() method because I don't know how many div I'll have in my page.
开发者_运维知识库Anyone have any suggestions to "fix" this problem?
All you need to do is remove the class 'MyClass' from div2. Then it won't match the selector for the live binding.
Here's an example
something else to try:
$('.mySelector').unbind('click');
One "hotfix" solution would be this:
$('.MyClass').live('click', function(evt) {
if ( $(this).data('disabled') ) { return false; } // return if disabled
// do your stuff
});
And then, when you want to disable a DIV, do this:
$('#div2').data('disabled', true);
Now, the live-handler will still execute, but it will immediately return.
You can even re-enable it later by setting the above data-attribute to true
.
精彩评论