简体   繁体   中英

Understanding jQuery (basic question)

i have a pretty basic jquery question. im trying to add jscrollpane to my site and get it to initialize after an ajax call. however when i run the function i keep getting the message "testFunction is not defined" in the console. the code is very basic:

$(document).ready(function() {
  var api = $('.scroll-pane').jScrollPane({
      showArrows:true,
      maintainPosition: false
    }).data('jsp');

  function testFunction() {
      api.getContentPane().load('ajax_content.html', function() {
      api.reinitialise();
   });
 }          
});

why do i keep getting the message? if i take the testfunction out of the document ready function i get the error "api not defined" thanks in advance

This has to do with the scope of the variable api that you are defining. You need to define the api variable outside of the $(document).ready(function() { ... . Try this:

var api;
$(document).ready(function() {
  api = $('.scroll-pane').jScrollPane({
      showArrows:true,
      maintainPosition: false
  }).data('jsp');
});

function testFunction() {
    api.getContentPane().load('ajax_content.html', function() {
        api.reinitialise();
    });
}

Hopefully that helps.

I think that is because the scope of the test function is now the anonymous function you call on document ready. Declare testFunction outside that anonymous function.

The 'not defined' message is coming from code that is using testFunction but is not waiting until it is defined. You have enclosed the definition of testFunction in the documentReady event but not the user of testFunction.

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