2

我想调用一个回调方法,该方法可能会或可能不会在 jQuery 选项卡作为 Ajax 内容加载的页面中实现。换句话说,我有一组 jQuery 选项卡,用于加载在 JSP 文件中呈现的内容。其中一些文件中包含额外的 Ajax 内容,有些则没有。

我能做的是:

$(document).ready(function() {
    $("#menu").tabs( {
        cache: false,
        ajaxOptions: {cache: false},
        load: function(event, ui) {
            if (ui.index == index_of_tab_with_additional_content) {
                //call code defined in other places and embedded using <script> tags
            }
        }
    });
});

但这有一些缺点——所有回调必须在嵌入到我的主选项卡页面的脚本中声明,以及它们可能依赖的任何东西——不优雅!另外,我希望能够调用相同的回调,以避免逐页 if/else 语句。简而言之,我想要类似的东西

load: function(event, ui) {
        callback();   //Each tab would implement this differently, or not at all
    }
}

可悲的是,我无法弄清楚如何调用内容中声明的脚本函数。如其他线程中所述,jQuery 不加载 Javascript。

显然必须为此设置一个选项,但我找不到哪个选项。

如果设置了选项并加载了 JS,我将如何访问这些功能?会不会是 ui.panel.funcname(); ?

谢谢, ES

4

1 回答 1

3

JQuery will not load script content located in the header of the document being loaded via AJAX, but it will load script content from the body. The easiest way to handle this if you don't want the code on the main page (using live handlers) is to have your main page load any external script files required by any tabs and have the content for each tab contain the "callback" mechanism for what needs to be done when the tab is loaded. You need to be careful, realizing that all tabs may be loaded in the DOM at once necessitating naming distinctions between tabs and, perhaps, qualifying any selectors so that they are relative to the tab container, but it is doable.

Ex.

  <html>
  <head>
      ...
      <script type="text/javascript">
          // I'm not going to be loaded via AJAX
      </script>
  </head>
  <body>
  <div id="homeTab" class="tab-content">
       ...
       <a href="#" class="clickable button">Click Me</a>
       ...
  </div>
  <script type="text/javascript">
      $(function() {
          // here be stuff which runs when the tab is loaded
          var $tab = $('#homeTab');
          $('a.button',$tab).click( function() {
              ...do something...
              return false;
          });
      });
  </script>
  </body>
  </html>
于 2010-03-29T21:27:25.833 回答