Question

I was attached the JQuery UI Selectable to an UL element.But the li item which inside were dynamic created.And of course, I couldn't make selection of them.So, How to attach plugin's function to dynamic created elements in JQuery!?

E.g:

<ul id="selectable">
    <li class="dataItem">item dynamic created here but you can't select me</li>

</ul>

[update]

JQuery code:

$( "#selectable" ).selectable();

and where I use delegate or live!?

the way the delegate and live usage is to bind events in this way:

$('#selectable').delegate('li','click',function(){
  // do something here
});

but the selectable plugin's events are:

Supply a callback function to handle the selected event as an init option.

$( ".selectable" ).selectable({
   selected: function(event, ui) { ... }
});

and the newly added item didn't get the selectable plugin's state like:

ui-selectee

So,should I re-attach the plugin at every time when a new item added!?

Thank you very much!!

Was it helpful?

Solution

use .live() or .delegate()


well, for your update, call $( "#selectable" ).selectable(); right after the time you have attach #selectable element in the DOM.

for example,

$('#selectable').click(function(){
    alert('I will not fire');
});

$('body').append('<ul id="selectable"><li class="dataItem">item</li></ul>');

$('#selectable').click(function(){
    alert('I will fire');
});

alert('I will fire'); will be the only alert triggered.

OTHER TIPS

jQuery offers .live which will do exactly what you want.

"Attach a handler to the event for all elements which match the current selector, now and in the future."

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top