jEasyUI 动态添加标签页
核对 Tabs 组件的 exists、select 与 add 方法组合逻辑,以及使用 iframe 动态挂载可关闭标签页并避免重复创建的离线实测行为。
学完这一章,你能够
- 核对 Tabs 组件的 exists、select 与 add 方法组合逻辑,以及使用 iframe 动态挂载可关闭标签页并避免重复创建的离线实测行为。
动态添加标签页的核心思路
在多视图单页后台中,jQuery EasyUI 的 Tabs 组件允许在运行期调用 `add` 方法动态插入面板,并以 `iframe` 承载外部或子页面内容。点击触发按钮时,若目标标题尚未打开则新建标签页;若已存在则直接切换激活,避免同一页面被重复挂载。
声明初始容器与实现 addTab 逻辑
第一步只需用 HTML 声明触发按钮与 Tabs 容器:在上方放置带 `easyui-linkbutton` 样式的链接按钮(分别触发 `google`、`jquery`、`easyui`),下方使用 `id="tt"` 与 `class="easyui-tabs"` 设定 `400px × 250px` 容器,并内置一个默认不可关闭的 `Home` 面板,初始阶段无需额外 JavaScript 代码。本站 Chromium 实测初始渲染容器精确为 `400 × 250` 像素,仅激活 `Home` 且其 `closable` 为 `false`。
第二步编写 `addTab(title, url)`:先调用 `$('#tt').tabs('exists', title)` 判重,已存在时执行 `select` 激活对应面板;不存在时拼接占满面板宽高(`width:100%;height:100%`、`frameborder="0"`、`scrolling="auto"`)的 `iframe` 字符串并调用 `tabs('add', {title, content, closable: true})`。本站离线实测依次点击 `jquery` 与 `easyui` 后标签数增至 3(`['Home', 'jquery', 'easyui']`)并选中 `easyui`;再次点击 `jquery` 时 `exists` 为真仅切换激活而不重复新增,点击关闭按钮后 `jquery` 移除且 `exists('jquery')` 恢复 `false`。
参考示例包 `jeasyui-layout-tabs2.zip` 保持不发起外网请求,已登记为本地替代证据;本站提供的独立 Playwright Chromium 离线实验脚本完整覆盖初始挂载、动态新增、重复激活与关闭销毁全流程。
运行动态添加、判重激活与关闭 iframe 标签页的离线 Chromium 实验
展开查看收起
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 18: Dynamic Tabs."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>EasyUI Dynamic Tabs Offline Lab</title>
<style>
body { font-family: sans-serif; margin: 12px; }
.toolbar { margin-bottom: 10px; }
.easyui-linkbutton { display: inline-block; padding: 4px 10px; margin-right: 6px; border: 1px solid #95b8e7; background: #eaf2ff; color: #0e2d5f; text-decoration: none; border-radius: 3px; cursor: pointer; }
.easyui-tabs { border: 1px solid #95b8e7; display: flex; flex-direction: column; box-sizing: border-box; }
.tabs-header { display: flex; background: #e0ecff; border-bottom: 1px solid #95b8e7; padding: 4px 4px 0; gap: 4px; }
.tabs-tab { display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; border: 1px solid #95b8e7; border-bottom: none; background: #f4f8ff; cursor: pointer; font-size: 13px; }
.tabs-tab.tabs-selected { background: #fff; font-weight: 600; }
.tabs-close { border: none; background: transparent; cursor: pointer; font-size: 12px; color: #666; padding: 0 2px; }
.tabs-panels { flex: 1; position: relative; }
.tabs-panel { width: 100%; height: 100%; display: none; box-sizing: border-box; }
.tabs-panel.active { display: block; }
</style>
</head>
<body>
<div class="toolbar" style="margin-bottom:10px">
<a href="#" id="btn-google" class="easyui-linkbutton" onclick="addTab('google','data:text/html,<h1>Google Offline</h1>');return false;">google</a>
<a href="#" id="btn-jquery" class="easyui-linkbutton" onclick="addTab('jquery','data:text/html,<h1>jQuery Offline</h1>');return false;">jquery</a>
<a href="#" id="btn-easyui" class="easyui-linkbutton" onclick="addTab('easyui','data:text/html,<h1>EasyUI Offline</h1>');return false;">easyui</a>
</div>
<div id="tt" class="easyui-tabs" style="width:400px;height:250px;">
<div title="Home">Welcome Home</div>
</div>
<script>
(function(){
const container = document.getElementById('tt');
const initialDivs = Array.from(container.children);
container.innerHTML = '<div class="tabs-header"></div><div class="tabs-panels"></div>';
const header = container.querySelector('.tabs-header');
const panelsEl = container.querySelector('.tabs-panels');
const tabList = [];
let selectedTitle = null;
function renderSelect(title) {
selectedTitle = title;
tabList.forEach(item => {
const isSel = item.title === title;
item.tabEl.classList.toggle('tabs-selected', isSel);
item.panelEl.classList.toggle('active', isSel);
});
}
function closeTab(title) {
const idx = tabList.findIndex(t => t.title === title);
if (idx === -1) return;
const [removed] = tabList.splice(idx, 1);
removed.tabEl.remove();
removed.panelEl.remove();
if (selectedTitle === title) {
const next = tabList[Math.max(0, idx - 1)];
renderSelect(next ? next.title : null);
}
}
function createTab(opts) {
const tabEl = document.createElement('div');
tabEl.className = 'tabs-tab';
tabEl.dataset.title = opts.title;
const label = document.createElement('span');
label.textContent = opts.title;
tabEl.appendChild(label);
tabEl.addEventListener('click', () => renderSelect(opts.title));
if (opts.closable) {
const closeBtn = document.createElement('button');
closeBtn.type = 'button';
closeBtn.className = 'tabs-close';
closeBtn.textContent = '×';
closeBtn.dataset.closeTitle = opts.title;
closeBtn.addEventListener('click', e => {
e.stopPropagation();
closeTab(opts.title);
});
tabEl.appendChild(closeBtn);
}
const panelEl = document.createElement('div');
panelEl.className = 'tabs-panel';
panelEl.dataset.title = opts.title;
panelEl.innerHTML = opts.content || '';
header.appendChild(tabEl);
panelsEl.appendChild(panelEl);
tabList.push({ title: opts.title, closable: Boolean(opts.closable), tabEl, panelEl });
renderSelect(opts.title);
}
initialDivs.forEach(div => {
createTab({ title: div.getAttribute('title'), content: div.innerHTML, closable: div.getAttribute('closable') === 'true' });
});
window.tabsApi = {
exists(title) { return tabList.some(t => t.title === title); },
select(title) { if (this.exists(title)) renderSelect(title); },
add(opts) { createTab(opts); },
close(title) { closeTab(title); },
state() {
return {
titles: tabList.map(t => t.title),
closableMap: Object.fromEntries(tabList.map(t => [t.title, t.closable])),
selected: selectedTitle,
iframeCount: panelsEl.querySelectorAll('iframe').length,
};
}
};
window.addTab = function(title, url) {
if (window.tabsApi.exists(title)) {
window.tabsApi.select(title);
} else {
const content = '<iframe scrolling="auto" frameborder="0" src="' + url + '" style="width:100%;height:100%;"></iframe>';
window.tabsApi.add({ title: title, content: content, closable: true });
}
};
})();
</script>
</body>
</html>
"""
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page(viewport={"width": 800, "height": 500})
page.set_content(HTML_DOC)
# Case 1: Initial Home tab & 3 linkbutton triggers
res1 = page.evaluate("""() => {
const box = document.getElementById('tt').getBoundingClientRect();
const btns = Array.from(document.querySelectorAll('.easyui-linkbutton')).map(a => a.textContent.trim());
const st = window.tabsApi.state();
return {
width: Math.round(box.width),
height: Math.round(box.height),
buttons: btns,
titles: st.titles,
selected: st.selected,
homeClosable: st.closableMap.Home,
};
}""")
exp1 = {
"width": 400,
"height": 250,
"buttons": ["google", "jquery", "easyui"],
"titles": ["Home"],
"selected": "Home",
"homeClosable": False,
}
cases.append(dict(name="initial_home_tab_and_add_buttons", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: Dynamic add creates closable iframe tabs and activates latest
before_exists = page.evaluate("() => window.tabsApi.exists('jquery')")
page.click("#btn-jquery")
page.click("#btn-easyui")
res2 = page.evaluate("""(beforeExists) => {
const st = window.tabsApi.state();
const iframe = document.querySelector('.tabs-panel[data-title="jquery"] iframe');
return {
beforeExists,
afterExists: window.tabsApi.exists('jquery'),
titles: st.titles,
selected: st.selected,
closableMap: st.closableMap,
iframeCount: st.iframeCount,
iframeAttrs: {
scrolling: iframe.getAttribute('scrolling'),
frameborder: iframe.getAttribute('frameborder'),
widthStyle: iframe.style.width,
heightStyle: iframe.style.height,
}
};
}""", before_exists)
exp2 = {
"beforeExists": False,
"afterExists": True,
"titles": ["Home", "jquery", "easyui"],
"selected": "easyui",
"closableMap": {"Home": False, "jquery": True, "easyui": True},
"iframeCount": 2,
"iframeAttrs": {
"scrolling": "auto",
"frameborder": "0",
"widthStyle": "100%",
"heightStyle": "100%",
},
}
cases.append(dict(name="dynamic_add_iframe_tab_and_closable", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: Duplicate click selects existing tab without duplicating; close button removes tab
page.click("#btn-jquery")
after_dup = page.evaluate("() => window.tabsApi.state()")
page.click('button.tabs-close[data-close-title="jquery"]')
after_close = page.evaluate("() => ({ state: window.tabsApi.state(), jqueryExists: window.tabsApi.exists('jquery') })")
res3 = {
"afterDuplicateTitles": after_dup["titles"],
"afterDuplicateSelected": after_dup["selected"],
"afterCloseTitles": after_close["state"]["titles"],
"afterCloseSelected": after_close["state"]["selected"],
"jqueryExistsAfterClose": after_close["jqueryExists"],
}
exp3 = {
"afterDuplicateTitles": ["Home", "jquery", "easyui"],
"afterDuplicateSelected": "jquery",
"afterCloseTitles": ["Home", "easyui"],
"afterCloseSelected": "Home",
"jqueryExistsAfterClose": False,
}
cases.append(dict(name="duplicate_tab_activates_and_close_removes", expected=exp3, actual=res3, passed=(res3 == exp3)))
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
若不先用 `exists` 判重,重复点击同一菜单或按钮会不断创建同名面板并重复加载 `iframe` 资源;配合 `select` 可直接切回已有面板并节省内存。