r114/app.js · 约 3039 字符
1
2(function () {
3 var $ = function (s, r) { return (r || document).querySelector(s); };
4 var $$ = function (s, r) { return Array.prototype.slice.call((r || document).querySelectorAll(s)); };
5
6 // 数据源:优先 fetch json,失败回落 window.__DATA__
7 var DS = {
8 _c: {},
9 get: function (name, cb) {
10 var self = this;
11 if (self._c[name]) { cb && cb(self._c[name]); return; }
12 fetch('data/' + name + '.json')
13 .then(function (r) { return r.json(); })
14 .then(function (d) { self._c[name] = d; cb && cb(d); })
15 .catch(function () {
16 var fb = (window.__DATA__ && window.__DATA__[name]) || null;
17 self._c[name] = fb; cb && cb(fb);
18 });
19 },
20 all: function (names, cb) {
21 var self = this, out = {}, n = names.length, done = 0;
22 names.forEach(function (nm) {
23 self.get(nm, function (d) { out[nm] = d; done++; if (done === n) cb(out); });
24 });
25 }
26 };
27
28 function esc(s) {
29 if (s === null || s === undefined) return '';
30 return String(s).replace(/[&<>"']/g, function (m) {
31 return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m];
32 });
33 }
34 function fmt(n) { n = Number(n) || 0; return n.toLocaleString('zh-CN'); }
35
36 var toastT;
37 function toast(msg) {
38 var t = $('#toast'); if (!t) return;
39 t.textContent = msg; t.className = 'toast show';
40 clearTimeout(toastT);
41 toastT = setTimeout(function () { t.className = 'toast'; }, 1800);
42 }
43 function fail(msg) { toast(msg || '功能演示,敬请期待'); }
44
45 // 通用点击委托
46 document.addEventListener('click', function (e) {
47 // 分段切换(seg 控件,data-group 分组,对应 .seg-panel[data-val])
48 var seg = e.target.closest('.seg');
49 if (seg) {
50 e.preventDefault();
51 var g = seg.getAttribute('data-group'), v = seg.getAttribute('data-val');
52 $$('.seg[data-group="' + g + '"]').forEach(function (x) { x.classList.remove('on'); });
53 seg.classList.add('on');
54 $$('.seg-panel[data-group="' + g + '"]').forEach(function (p) {
55 p.style.display = (p.getAttribute('data-val') === v) ? '' : 'none';
56 });
57 return;
58 }
59 var a = e.target.closest('[data-toast]');
60 if (a) { e.preventDefault(); fail(a.getAttribute('data-toast')); return; }
61 var c = e.target.closest('[data-confirm]');
62 if (c) {
63 e.preventDefault();
64 if (!window.confirm(c.getAttribute('data-confirm'))) return;
65 var to = c.getAttribute('data-confirm-toast');
66 if (to) toast(to);
67 }
68 });
69
70 // 底部 tab 高亮由页面 body[data-page] 控制,这里提供 seg 值读取
71 function segValue(group) {
72 var el = document.querySelector('.seg[data-group="' + group + '"].on');
73 return el ? el.getAttribute('data-val') : null;
74 }
75
76 window.$ = $; window.$$ = $$; window.DS = DS; window.esc = esc; window.fmt = fmt;
77 window.toast = toast; window.fail = fail; window.segValue = segValue;
78})();
79