Apply jQuery UI widgets to ajax loaded elements

后端 未结 3 899
感动是毒
感动是毒 2020-12-18 01:21

I want to activate the jQueryUI button widget on a given selector, lets say \'.button\'.

Whats the best way to automatically activate the widget on any new \'.button

相关标签:
3条回答
  • 2020-12-18 02:07

    You have a few options here. First, there's the liveQuery plugin, like this:

    $(.button).liveQuery(function() { $(this).button(); });
    

    Another alternative is to call the selector on your elements when you load them, this for example finds all .button only in the response, so doesn't mess with existing elements before the ajax call:

    $.ajax({
       url: 'page.html'
       success: function(data) {
         //stuff...
         $('.button', data).button();
       }
    });
    

    Another similar approach if you have a lot going on is to have your plugins in a function like this:

    function rigUI(context) {
      $('.button', context).button();
      $('.date', context).datepicker();
    }
    
    $(rigUI); // Load at document.ready, default context is document
    
    //in ajax load love above call: rigUI(data);
    
    0 讨论(0)
  • 2020-12-18 02:07

    Since all jquery commands have a uniform structure it is really easy to use any object (including json data from a ajax request) as a jquery command

    Sample:

    var jc = {
        'selector': '#sample',
        'method': 'dialog',
        'options': {'title': 'I am a sample'}
    }
    
    $(jc.selector)[jc.method](jc.options);
    

    is the same as

    $('#sample').dialog({'title': "I am a sample}};

    http://jsfiddle.net/wb5Ee/

    0 讨论(0)
  • 2020-12-18 02:14

    An alternative to liveQuery as it seemed outdated to me as I could not make it work :

    https://github.com/bapplistudio/jquery.build

    • You need to declare all your jquery activations into *$("body").build(function(){ }); * statements
    • You need to call $("newelement").build(); to call back all your initialisation functions.

    Look at the documentation on the jquery.build site for more information and examples and the live demo similar to your case.

    http://saf.re/github/jquery.build/examples/simple.html

    0 讨论(0)
提交回复
热议问题