简体   繁体   中英

Javascript not working in jQuery UI tabs that are loaded with Ajax

Javascript seems to be disabled in all jQuery UI tabs that are loaded through ajax. I am testing this with jQuery tooltips and .click() alerts. Javascript works fine in tabs that aren't loaded through ajax (IDs present on the page).

Here is how I am calling the tabs:

$(function() {
$('#foo-tabs').tabs(
{
heightStyle: 'content',
// Callback run when selecting a tab
beforeLoad: function(event, ui) {

// If the panel is already populated do nothing
if (ui.panel.children().size() > 0)
    return false;

//load specific ID within target page
ui.panel.load($('a', ui.tab).attr('href') + $('a', ui.tab).attr('data-target'));

// stop the default process (default ajax call should not be launched)
return false;
}
}
);
});

Here's the javascript I'm trying to activate:

$(function() {
$( '.activate-tooltip' ).tooltip();
});

And a test:

$(function() {
$("h1").click(function() {
alert("zomg javascript works!");
});
});

Any ideas on how to get javascript working in all ajax loaded tabs? Thank you for taking the time to go through this!

The problem is that at the time when your binding your events those elements are not present in the DOM. The way to deal with this is by delegating the events to a higher level DOM element (up to the Document if necessary) that does exist in the DOM.

For example to delegate using .on

$(document).on('click', 'h1', function() {
      alert("zomg javascript works!");
 });

For the tooltip plug in you can do something like the following

   $(function() {
        //initialize tooltip plugin
        //dvCont is just an existing element in the DOM, you can use #foo-tabs
        $('#dvCont').tooltip({
            items: '.activate-tooltip',
            content: function(){
                var element = $( this );
               if ( element.is( ".activate-tooltip" ) ) {
                return 'Some text';
                }
                if ( element.is( "[title]" ) ) {
                  return element.attr( "title" );
               }

             }
          });

      $('#dvCont').append($('<div class="activate-tooltip" >Test</div>')); //dynamic content

    });

Here's a link to a jsBin

You can see a more complete example on the Demo page for the plugin.

Edit:

In response to why you should use event delegation if you can just initialize the plugin right after you add it to the DOM, I think its worth pointing out that besides for handling dynamic content another reason to use event delegation is due to performance. That is with event delegation you are able to attach fewer event handlers which in turn means less memory used.

To illustrate here's a link to a jsPerf that compares using event delegation vs binding directly.

When you call a method such as .click() , it adds the event handler directly to all of the elements in the jQuery object (ie those that matched the selector at the time it was run ). When you add new elements to the page they don't have the associated event handlers, because they didn't exist when that code was executed.

The solution is event delegation; the general principle is that you set the event handler on an element higher up the DOM tree - one that contains all of the elements you wish to match. Then, when an event of that type is triggered on an element inside it and bubbles up to the element with the handler, it checks to see if the triggering element meets the conditions; if it does, it executes the callback function.

However, this only works for event handlers, it won't work for plugins. I don't know of a way to delegate plugin initialisation, so you'll likely just have to execute the code again. Thankfully the .load() function takes a callback function which will run when the new tabs content has finished being loaded via AJAX.

ui.panel.load($('a', ui.tab).attr('href') + $('a', ui.tab).attr('data-target'), function() {
    $('.activate-tooltip', ui.panel).tooltip();
});

You could use on function of jquery to trigger click event for dynamically created html(in your case its the ajax function which creates dynamic html(tabs)). `

$("h1").on("click", function(){ alert("zomg javascript works!"); });

`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM