我在 Web 应用程序中使用 jQuery UI 选项卡,并且通过 Ajax 动态加载每个选项卡的内容。这样,我可以将每个选项卡的内容保留在单独的 HTML 页面中:
<div id="tabs">
<ul>
<li><a href="ajax/content1.html">Tab 1</a></li>
<li><a href="ajax/content2.html">Tab 2</a></li>
<li><a href="ajax/content3.html">Tab 3</a></li>
<li><a href="ajax/content4.html">Tab 4</a></li>
</ul>
</div>
实例化选项卡的 JavaScript 位于我的 index.js 中,HTML 位于 index.html 中。
现在,我想在 index.js 中创建一个 addTabs() 函数,可以从任何选项卡内容页面(content1.html、content2.html 等)调用该函数。
我该怎么做?我尝试在 index.js 中创建该函数,然后简单地使用 var id = addTab(); 调用它。但这不起作用,因为我收到了一个错误:“Uncaught ReferenceError:addTab 未定义”。这是函数:
function addTab(tabTitle) {
// Add tab code
return id;
}
我还尝试使用 $.getScript()
来调用该函数,但我无法使用 $ 之外返回的内容访问
函数(我只能在函数内访问它)。var id
.getScript()
如果您能就此事提供帮助,我将不胜感激。
<小时/>这是index.js 文件:
$(document).ready(
function () {
var tabs = $("#tabs").tabs();
tabs.tabs('option', 'selected', 2);
var tabTemplate = "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>";
var tabCounter = 4;
function addTab(tabTitle) {
var label = tabTitle;
var id = "tabs-" + tabCounter;
var li = $(tabTemplate.replace(/#\{href\}/g, "#" + id).replace(/#\{label\}/g, label));
// 3 fixed tabs + 5 dynamic tabs
if (tabCounter > 8) {
$("#dialog").html(
'You have reached the maximum number of tabs allowed.').dialog(
"open");
return -1;
}
$("#tabId").replaceWith(
'<input type="hidden" name="tabId" id="tabId" value="' + id
+ '" />');
tabs.find(".ui-tabs-nav").append(li);
tabs.append("<div id='" + id + "'></div>");
tabs.tabs("refresh");
tabCounter++;
return id;
}
});
最佳答案
addTab 函数应该位于 document.ready 之外,以便其他文件可以访问它
关于从 jQuery UI 选项卡内容访问 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14364289/