Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

html - Local links in document embedder inside iframe

I have couple of documentation pages that I wrote in ordinary markdown file and then exported to HTML. The documents are placed in subdirectories. I've generated tree menu using tree.js and I'm loading those documents in an <iframe> whenever the hash of the address changes. I have several problems with this approach, but at the moment let's say the main issue is that I can't get local links to work (those that jump you to a paragraph).

Some pages have linked images, with addresses relative to the physical page location (which is not what is reflected by address bar) so I've set the <base> for the links in the iframe an this seem to work fine:

function setLinksBaseForDocIFrame() {
        var path = dataRoot + document.location.hash.substr(1);
        path = path.substr("...".length);
        $("#docFrame").contents().find("head")
            .prepend("<base href="..." + path + "/doc/"/>")
            .append("<base target="_blank" />");
    }

But now I have problems with those local links. I'm using Typora to generate those HTML pages. The links look like this:

<a href="#declare-current-operation-options"><span>Declare options</span></a>

An the href is added to that base, so my idea was to find all the links staring with#...and replace it with something like #$... and then on address change I would detect that this is local link and manually scroll to the element with that name using $("a[name='" + n + "']").get(0).scrollIntoView();.

So, I'm failing with changing those links using Jquery. I've tried something like that:

function adaptLocalAnchorsLinks() {
    var f = $("#docFrame").contents().find("body"); 
    var a = f.contents().find('a'); 
    $('a').each(function () {
        var $this = $(this),
            aHref = $this.attr('href');
        if (aHref === undefined) return;
        if (!aHref.startsWith("#")) return;
        var n = aHref.replace("#", "#$");
        $this.attr("href", n);
    });
}

Which is what I found on some page (I'm not a web developer by any means).

First, I don't know why .find('a'); doesn't return anything but when I changed the a to $('a') the function seem to be invoked, however the aHref is always undefined. What am I doing wrong?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...