代码之家  ›  专栏  ›  技术社区  ›  jeje

在jQuery隐式上下文中运行函数

  •  0
  • jeje  · 技术社区  · 14 年前

    我的html文档如下:

    <html>
     <head> .. load jquery and other stuff </head>
     <body>
       <div id="cool_container">
        <div class="cool">.. no script friendly markup ..</div>
       </div>
       <a id="cool_link">Link</a>
     <script>
        function installStuff(){
            $('.cool').coolPlugin();
            $('#cool_link').click(function(){
                    $('#cool_container').load('/anothercooldiv.html');
            });
        }
        $(document).load(function(){ installStuff(); });
     </script>
    
     </body>
    </html>
    

    /anothercooldiv.html 再给一个 <div class="cool"> .. etc ...</div> 碎片。

    那么,在不破坏一切的情况下(以及编写一些讨厌的黑客),将fresh cool div变成coolPlugin的最佳方法是什么?

    如果能做到:

    • $.doThisInContext(function(){installStuff();}, $('#cool_container');

    load

    • 或者,有一个等价的“Live”(这将解决链接的问题,如果酷包含链接),但在元素的存在,我可以使用这样的函数安装程序:

      $('.cool').exists(function(what){ what.coolPlugin() };

    然后 coolPlugin 将安装在所有 cool 现在和将来的元素。

    2 回复  |  直到 14 年前
        1
  •  2
  •   Nick Craver    14 年前

    我建议 .livequery() plugin 对于这个仍然:

    $(function() {
        $('.cool').livequery(function() {
          $(this).coolPlugin();
        });
        $('#cool_link').click(function(){
                $('#cool_container').load('/anothercooldiv.html');
        });
    });
    

    重要的一点是:

    $('.cool').livequery(function() {
      $(this).coolPlugin();
    });
    

    .cool 元素,在每个元素上运行插件。

        2
  •  0
  •   Karl Rosaen    14 年前

    将插件应用于新加载的ajax内容应该不会太复杂:

    $('#cool_container').load('/anothercooldiv.html', function() {
       $(this).coolPlugin();
    });