简体   繁体   English

我可以链接到dom中的元素吗

[英]Can i link to an element in the dom

I have a static web page consisting of text, broken up into sections with <h2> tags. 我有一个包含文字的静态网页,并用<h2>标签分成多个部分。 I don't have access to the underlying code, but I'd like to link to a specific <h2> tag. 我无权访问基础代码,但我想链接到特定的<h2>标签。 If I had access to the code I could either mark the tags up with IDs for example: <p id="section1"> - but that's not an option. 如果我可以访问代码,则可以用ID标记标签,例如: <p id="section1"> -但这不是一个选择。 I could also access them using the DOM index eg document.getElementsByTagName("h2")[0] - so my question really is, is there any way of adding that to a link without needing the associated javascript? 我还可以使用DOM索引访问它们,例如document.getElementsByTagName("h2")[0] -所以我的问题是,有没有办法将其添加到链接中而不需要相关的javascript?

Thanks 谢谢

Ali 阿里

No, you can't do that with just a link. 不,您不能仅仅通过链接来做到这一点。

In one way or the other you need access to the underlaying markup, to either scroll to a position or do a live update of the DOM. 您需要以一种或另一种方式访问​​底层标记,才能滚动到某个位置或实时更新DOM。

If you can get access to it using an iframe and CORS is not blocking, it could be done that way. 如果您可以使用iframe访问它,并且CORS没有阻塞,则可以通过这种方式完成。

Another way could be to use a server side language, like ASP.NET, from where you read the page, process it and then forward it to the client. 另一种方法可能是使用服务器端语言,例如ASP.NET,从那里您可以读取页面,对其进行处理,然后将其转发给客户端。 This can still backfire depending on how scripts etc. will act on the page in question. 这仍然会适得其反,具体取决于脚本等在相关页面上的行为方式。

<iframe id="myframe" src="/yourDocument.html" />
var x = document.getElementById("myframe");
var y = (x.contentWindow || x.contentDocument);
if (y.document)y = y.document;
var contLinks = y.body;

as explained here: IFrame contentDocument Property 如此处所述: IFrame contentDocument属性

If you can open the document on an iframe like so or get it's content from a server side script, run this on the returned DOM: 如果您可以像这样在iframe上打开文档,或者从服务器端脚本获取文档的内容,请在返回的DOM上运行此文档:

var createLinks = function(){
    var contLinks = document.getElementsByTagName("body");
    for(i=0; i<contLinks.length; i++)
        {
            var Links = document.getElementsByTagName("h2");
            var appendLinks = "";
            for(idx=0; idx<Links.length; idx++)
                {
                    appendLinks += "<a href='"+Links[idx].innerHTML.trim()+"'>"+Links[idx].innerHTML.trim()+"</a><br/>";
                    //Links[idx].remove;
                }
            contLinks[i].innerHTML = appendLinks;
        }
  }
 createLinks();

Direct the last line contLinks[i].innerHTML = appendLinks; contLinks[i].innerHTML = appendLinks;最后一行contLinks[i].innerHTML = appendLinks; to the output that you prefer... 到您喜欢的输出...

If you definitely can't use any kind of interaction with the document, then you just can't use it. 如果您绝对不能与文档进行任何形式的交互,那么您就无法使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM