qinHaiXiang
qinHaiXiang

Reputation: 6419

How to rebind event to dynamic created elements in jquery plugin?

I am creating a plugin and got something problems:

in the case:

I have a list of un-list created by ajax loaded .such as :

<ul id='ulist'>
    <li>list 1</li>
    <li>list 2</li>
    <li>list 3</li>
</ul>

then li were binded with hover event when they loaded. such as :

$('ul').bind('hover',function(){});

but my plugin had a function to dynamic adding new li item to the ul[id='ulist'] which had been loaded.and the new li didn't get the hover event binding.Such as:

addNewLi : function(){
    $('<li />').html('item N').appendTo('#ulist');
}

So,I knew I should bind the new dynamic created elements by 'live',but I don't know where to put it or have other way ....

Thank you very much!!

Upvotes: 1

Views: 698

Answers (1)

lonesomeday
lonesomeday

Reputation: 237865

You can't use the twin handler functionality of hover in live or delegate. That functionality is, I believe, planned for jQuery 1.5.

However, hover is actually only a shortcut for the two events mouseenter and mouseleave, so it's actually very easy to mimic the functionality using these events.

Example using delegate:

$('#ulist').delegate('li', 'mouseenter', function() {
    // code for mouseenter
}).delegate('li', 'mouseleave', function() {
    // code for mouseleave
});

Upvotes: 1

Related Questions