javascript - 在所有页面中搜索具有唯一 ID 的 <body>

标签 javascript jquery html

是否可以在您开发的所有网页(而不仅仅是用户所在的当前页面)中搜索具有指定 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/

相关文章:

javascript - 如何在 Bootstrap Material 设计的输入文本中制作标签支持?

html - 下拉列表 html 和 css

javascript - 将jquery数据存储在html元素中

javascript - 检查列获取计数

javascript - 如何在 JavaScript 中隐藏某个类

javascript - 为什么我不能在@NgModule 中导入 Angular 2 服务?

javascript - 为什么 jquery $.ajax 会删除数据中的换行符而 $.get 不会?

javascript - 函数作为参数的 JavaScript 语法

javascript - 通过调整窗口大小来缩放和维护 DIV 位置

css - div 元素中链接之间的空间