我在 Phonegap 中为我的 android/ios 应用程序使用 jquery、jquery mobile、js、html 和 css。
我对 js 和 jquery 的掌握非常有限。
我的 index.html 使用 .load 将其他 html 文件调用到它们的同名 div 中。
有没有办法替换下面的代码:
$('#page01001').load('cards/01001.html');
$('#page01002').load('cards/01002.html');
$('#page01003').load('cards/01003.html');
$('#page01004').load('cards/01004.html');
..
$('#page01900').load('cards/01900.html');
(它占用了我的 .js 文件的将近 2000 行),只有一条规则会执行类似以下操作:
$('#pageIDENTIFIER').load('cards/IDENTIFIER.html');
这样任何名为“pageWHATEVER”的 div 都会加载同名的 html 文件(减去“page”一词)?
我已经阅读了 jquery 通配符,但找不到一种方法来获取通配符输入并将其复制到命令的第二部分。
稍微复杂一点的是,index.html 中通常有几个地方引用同一个 html 文件:
$('#page01001').load('cards/01001.html');
$('#pageX01001').load('cards/01001.html');
$('#pageH01001').load('cards/01001.html');
所以 div“page01001”、“pageX01001”和“pageH01001”都需要加载 01001.html
而且,有很多 div 只是 div,不需要 .load 任何东西。我不想影响那些。只有名称以“page..”开头的 div 需要 .load。
有什么方法可以改进吗?
最佳答案
使用 .each()
循环和正则表达式从 ID 中提取页码。
$("div[id^=page]").each(function() {
var match = this.id.match(/\d+$/)[0];
$(this).load('cards/' + match + '.html');
});
关于javascript - 一种使用 .load 和通配符的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46009581/