Learning .delegate() on function... Can't use .bind
Heres the jsfiddle, jsfiddle.net/kqreJ
So I was using .bind no problem for this function but then I loaded more updates to the page and found out that .bind doesn't work for content imported to the page but just for content already on the page! Great!
So I switched it up to .delegate which is pretty cool but now I can't figure out how to .bind .unbind my function the way it was???
$('#maindiv').undelegate(".open","mouseup").delegate(".open","mouseup",function(event){
var $this = $(this), h开发者_StackOverflow社区andler = arguments.callee;
$this.unbind('mouseup', handler);
var id = $(this).attr("id");
var create = 'nope';
var regex = /\d+$/,
statusId = $('#maindiv .open').toArray().map(function(e){
return parseInt(e.id.match(regex));
});
var divsToCreate = [ parseInt(id) ];
$.each(divsToCreate, function(i,e)
{
if ( $.inArray(e, statusId) == -1 ) {
create = 'yup';
}
});
if( create == 'yup' ) {
if(id) {
$.ajax({
type: "POST",
url: "../includes/open.php",
data: "post="+ id,
cache: false,
success: function(html) {
$('.open').html(html);
$this.click(handler);
}
});
}
}
});
You can see by the demo that it still creates multiple instances and isn't binding? Racked my brain trying to figure this out.
Change bind
to live
and change nothing else... see if it works.
live()
binds dynamically loaded content as well like delegate
.
to unbind live
I believe you use die
.
Update
This is how I would do it assuming that all you want to do is onClick
add a div if it doesn't already exist on the page and if the div does exist highlight it. I had to throw out your old code, it was too confusing, I went strictly by your requirement.
Keep in mind that since delegate is dynamically, it is bound to your selector, remove the class or change the id and binding is automatically removed from that class. In my example I have 2 delegate methods. Basically by changing the class I change the function being called.
精彩评论