【问题标题】:innerHTML containing bookmarks cannot be linked to from another page不能从另一个页面链接到包含书签的 innerHTML
【发布时间】:2021-01-28 02:11:25
【问题描述】:

我使用 JavaScript AJAX 将文件 cards.html 包含到父 html 页面 index.html 中。
包含的cards.html 文件是卡片列表,每张卡片中都有一个书签,格式为<li id="byx-123_shapes">。 当我从另一个页面超链接到书签时,而不是浏览器定位在书签上,它位于页面顶部。 如果我手动将cards.html 插入到 index.html 中,则超链接可以正常工作。 浏览器似乎不知道这些书签,因为它们是通过 AJAX 导入的,而不是在加载 index.html 时存在。

Cards.html 包含在 index.html 中。

    <section id="cards">
    <!-- INSERT CARDS HERE -->
    <ul>
    <li id="byx-123_shapes" class="byx-book-tile byx-box">
    
        <figure>
            <img src="books/123_shapes/res/icon.png">
        </figure>
        
        <h2>
            123 Shapes
        </h2>
        <p>
            Placeholder for a book that is still being written.
        </p>
        <a href="previews/123_shapes_view.html">Preview Book</a>
    </li>

    .... more cards ...

    <li id="byx-zoo_friends" class="byx-book-tile byx-box">
        
        <figure>
            <img src="books/zoo_friends/res/icon.png">
        </figure>
        
        <h2>
            Zoo Friends
        </h2>
        <p>
            Placeholder for a book that is still being written.
        </p>
        <a href="previews/zoo_friends_view.html">Preview Book</a>
    </li>
    </ul>
    </section>
...

JavaScript 加载cards.html

// Uses AJAX to load cards.html
// Works but messes up card bookmarks
const xhr = new XMLHttpRequest();
const cards = document.getElementById('cards');
xhr.onload = function() {
    if (this.status == 200) {
        cards.innerHTML = xhr.responseText;
    } else {
        console.warn('Could not load cards');
    };
};
xhr.open('get', 'cards.html');
xhr.send();

通过 AJAX 包含时不起作用但手动插入卡片时起作用的超链接示例。

https://...//index.html#byx-zoo_friends

有人可以解释为什么会发生这种情况以及如何解决它。

【问题讨论】:

  • 定位是在 AJAX 请求完成之前发生的,所以页面中还没有书签。

标签: javascript html ajax innerhtml


【解决方案1】:

当您加载index.html#bookmark 时,它会在加载页面后立即尝试滚动到书签。但是 AJAX 请求还没有完成,所以书签没有加载。

您应该在xhr.onload 函数中添加代码以在插入 HTML 后滚动到书签

xhr.onload = function() {
    if (this.status == 200) {
        cards.innerHTML = xhr.responseText;
        if (window.location.hash) {
            let target = document.querySelector(window.location.hash);
            if (target) {
                target.scrollIntoView();
            }
        }
    } else {
        console.warn('Could not load cards');
    };
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-12
    • 2010-11-18
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多