我会尽量用几句话来解释我的问题。 我有一个HTML与各种iframes。在一个iframe中有一个目录(TOC),另一个是TOC中突出显示的相应元素的内容。由于存在各种TOC,可能发生的情况是,通过单击某个链接,我们将转到属于另一个TOC的主题,因此我希望TOC框架可以重新加载适当的TOC。为此,由于每个主题在TOC中都有唯一的ID,因此我会在所有TOC中搜索主框架中加载的主题的ID,并在找到想要的TOC时,将其加载到TOC框架中。用jquery在多个html文件中搜索字符串
至今我所编写的代码是seguent:
/*function called on load of each topic - it gets the topic unique id as parameter*/
function highlight(id) {
/*the names of the HTML files containing the different tocs*/
var tocs = ["toc.htm", "toc_documentazione.htm", "toc_flussiesteri.htm", "toc_garante.htm", "toc_legittimita.htm", "toc_normativa.htm", "toc_settori.htm", "toc_sicurezza.htm", "toc_sistemadp.htm", "toc_vistaarticolato.htm"]
var i = 0;
/*search within the different TOCs until you find a correspondence or there are no more TOCs*/
while (!changeTOC(tocs[i], "a" + id) && i < tocs.length) {
i = i + 1;
}
/*this line is probably wrong but the idea is to load the found TOC in the appropriate frame*/
$(content).load(tocs[i - 1] + " #content");
}
/*function using ajax to search the id into the HTML file passed as parameter (newToc) returning the search outcome*/
function changeTOC(newToc, id) {
var found = false;
$.get(newToc, "html").done(
function(temp_toc) {
/*if the HTML contains the id we search for we return true*/
if (temp_toc.indexOf(id) != -1)
found = true;
});
/*else we return false*/
return found;
}
我的问题是与while循环我使用过的各种TOC文件进行搜索。我做了一些调试,而且不管包含我正在搜索的id的TOC位于第一个位置,同时扩展了10个周期,并且只在最后它告诉我它找到了匹配的TOC,这是确实是名单中的第一个。
希望我已经能够让自己清楚。 感谢您的帮助
您正在试图从一个根本异步操作的函数内部返回值基本误差(即'changeTOC'调用'$ .get')。使用回调或jQuery承诺。你不能像这样在一个while循环中处理这些多个获取请求。 – 2014-10-08 16:20:13
看着这个问题,你真的需要找到另一种连接iFrame页面到TOC的方式。加载它们一次,只是为了找到链接,似乎不是很有效。 – 2014-10-08 16:25:42
谢谢@TrueBlueAussie。由于TOC文件是自动生成的,因此我没有很多关于文档结构的选择。这就是为什么我大量使用javascript和jquery来定制整体行为。我对JavaScript并不熟练,这就是为什么我会奋斗的原因,但我也会回顾一下回调和承诺 – miks87 2014-10-08 18:31:19