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

如何将jQuery应用于当前不可用的元素文件。准备好了吗?

  •  1
  • JasCav  · 技术社区  · 14 年前

    我正在开发的网站使用 jQuery UI tabs load content via AJAX

    // Theme all the buttons with jQuery UI themes.
    $('input:button').button();
    

    但是,选项卡上的所有按钮没有适当地设置主题。

    我该怎么解决这个问题?我在想一些关于 jQuery's .live() function ,但“load”和“ready”事件似乎都不起作用。这已成为一个相当令人沮丧的问题,所以任何可以提供的帮助将不胜感激。

    2 回复  |  直到 14 年前
        1
  •  0
  •   user113716    14 年前

    您可以将其应用于AJAX回调中的那些新元素:

    $.ajax({
        url:'/some/path',
        success: function( resp ) {
            var $newElements = $(resp);  //create jQuery object of new elements
            $newElements.find('input:button').button();  // call .button() on inputs
            $newElements.appendTo('body');  // append to wherever
        }
    });
    

    我不知道您的AJAX回调中发生了什么,但这应该会给您一个大致的想法。

        2
  •  1
  •   BBonifield    14 年前

    livequery插件( http://docs.jquery.com/Plugins/livequery )以前用过很多这样的东西。不过,这并不是处理问题的最有效方法。

    如果您是通过AJAX添加内容,为什么不在添加内容之后为其重新分配处理程序呢?

    // setup simple jQuery plugin to handle all of your custom logic (although this could be a normal function as well)
    $.fn.assignMyHandlers = function(){
        return this.each(function(){
            $(this).find('input:button').button();
            // etc
        });
    };
    
    // and then everywhere that you bring in AJAX'd content...
    $.get('test.html', function( html ) {
        var $fragment = $( html );
        $fragment.assignMyHandlers();
        $fragment.appendTo( "#theList" );
    });