是否可以在您开发的所有网页(不仅仅是用户所在的当前页面)中搜索具有指定 ID 的正文标签?如果是这样,我将如何在 Javascript 中执行此操作?另外,我将如何将用户重定向到包含具有唯一 ID 的正文的页面?
问问题
227 次
1 回答
3
如果你真的想这样做,如果你知道页面的 url,你可以这样做:
(使用 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'); };
于 2012-07-12T01:54:46.333 回答