0

開発したすべてのWebページ(ユーザーが表示している現在のページだけでなく)で、指定したIDのbodyタグを検索することはできますか?もしそうなら、Javascriptでこれをどのように行うのですか?また、一意のIDを持つその本文を含むページにユーザーをリダイレクトするにはどうすればよいですか?

4

1 に答える 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 に答える