【问题标题】:Jquery plugin how to implement .live or .on so it works with new elementsJquery 插件如何实现 .live 或 .on 使其适用于新元素
【发布时间】:2016-11-29 12:08:21
【问题描述】:

我有一个使用jQueryHTML 页面,还有一个外部插件tooltipster

为了初始化插件,我必须这样做:

 $(document).ready(function() {
    $('.tooltip').tooltipster();
});

HTML 非常简单,您只需将class 设置为"tootlip"

'<span class="tooltip" title="This is my spans tooltip message!">Some other text</span>'

这对于DOM 中的静态元素非常有效。

问题在于创建 DOM 后添加的新元素。 这与使用 .on().live() 后创建的元素时的 jQuery 类似。

如果我有:

 $('#newelement').click(function(e) {

                    $('#elements').html('<span class="tooltip" title="This is my spans tooltip message!">New element</span>');

                });

关于如何进行这项工作的任何线索?我可以将.on() 用于静态和动态元素吗?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

是的,对于新创建的元素,你最好使用:

$(document).on("click", "#newelement", function(e) {

                $('#elements').html('<span class="tooltip" title="This is my spans tooltip message!">New element</span>');

            });

【讨论】:

【解决方案2】:

最好的解决方案是在创建工具提示元素后立即重新绑定所有(或者如果您有雄心 - 仅新创建的)工具提示元素。例如,在 ajax 完成后,您应该刷新所有工具提示。

【讨论】:

    【解决方案3】:

    创建新函数并在 .on 事件中调用该函数

    //Here call the .on to    
    $("#anotherElement").on('click', function(){
         $('.tooltip').tooltipster();
         newFunction();
    });
    
    //Call the function to show title
    function newFunction(){
         $('#newelement'). click(function(e){
               $('#elements').h tml('<span class="tooltip" title="This is my spans tooltip message!">New element</span>');
         });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多