【问题标题】:How to attach plugin's function to dynamic created elements in JQuery?如何将插件的功能附加到 JQuery 中的动态创建元素?
【发布时间】:2011-02-15 03:39:04
【问题描述】:

我将JQuery UI Selectable 附加到UL element。但是内部的li item动态创建的。当然,我无法选择它们。所以,如何附上plugin's function to dynamic created elements in JQuery!?

例如:

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

</ul>

[更新]

JQuery 代码:

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

我在哪里使用delegatelive!?

delegatelive 的用法就是这样绑定事件:

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

selectable plugin's events 是:

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

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

并且新添加的项目没有获得selectable plugin's 状态,例如:

ui-selectee

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

非常感谢!!

【问题讨论】:

  • So,should I re-attach the plugin at every time when a new item added!? - 恐怕是的。

标签: jquery user-interface selectable


【解决方案1】:

jQuery 提供了.live,它将完全满足您的需求。

“将处理程序附加到与当前选择器匹配的所有元素的事件,现在和将来。”

【讨论】:

    【解决方案2】:

    使用.live().delegate()


    好吧,对于您的更新,请在您在 DOM 中附加 #selectable 元素之后立即调用 $( "#selectable" ).selectable();

    例如,

    $('#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'); 将是唯一触发的警报。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-29
      • 1970-01-01
      • 2016-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多