是否可以在您开发的所有网页(而不仅仅是用户所在的当前页面)中搜索具有指定 ID 的正文标记?如果是这样,我将如何在 Javascript 中做到这一点?另外,我将如何将用户重定向到包含具有唯一 ID 的正文的页面?
最佳答案
如果您确实想要这样做,如果您知道页面的网址,就可以做到:
(使用 jQuery)
function searchPages(urls,elem,success,failure){
nextUrl(urls,0);
// this calls itself as a callback because $.load is asynchronous
function nextUrl(i){ // this function tries to load a body#myId for the url
$('<div /'>).load(urls[i]+' '+elem,function(){
// if it loaded there'd be html
if($(this).html()!=='') success.call(this,urls[i]);
// if you've loaded all the pages, then you're done
if(i===urls.length)
failure.call(this,urls[i]);
// otherwise, call the function again for the next url
else nextUrl(i+1);
});
};
}
searchPages(['/url1','/url2','/url3'],'body#myId',function(url){
console.log(url); // this is the url you want
console.log($(this)); // $(this) is the div that the body elem was loaded into
},failed);
// this is called if you don't find the page
function failed(){ alert('no page found'); };
关于javascript - 在所有页面中搜索具有唯一 ID 的 <body>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11443962/